分类: C/C++
2007-06-06 23:44:07
Client:
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace MySocketClient1
{
public partial class Form1 : Form
{
private IPAddress serverIP = IPAddress.Parse("127.0.0.1");
private IPEndPoint serverFullAddr;
private Socket sock;
public Form1()
{
InitializeComponent();
}
private void btConnect_Click(object sender, EventArgs e)
{
try
{
serverFullAddr = new IPEndPoint(serverIP, 1000);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
sock.Connect(serverFullAddr);//建立与远程主机的连接
//启动新线程用于接收数据
Thread t = new Thread(new ThreadStart(ReceiveMsg));
t.Name = "Receive Message";
//一个线程或者是后台线程或者是前台线程。后台线程与前台线程类似,区别是后台线//程不会防止进程终止。一旦属于某一进程的所有前台线程都终止,公共语言运行库就//会通过对任何仍然处于活动状态的后台线程调用 Abort 来结束该进程。
t.IsBackground = true;
t.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiveMsg()
{
try
{
while (true)
{
byte[] byteRec = new byte[100];
this.sock.Receive(byteRec);
string strRec = System.Text.Encoding.UTF8.GetString(byteRec);
if (this.rtbReceive.InvokeRequired)
{
this.rtbReceive.Invoke(new EventHandler(ChangeRtb), new object[]
{ strRec, EventArgs.Empty });
}
}
}
catch(Exception ex)
{
MessageBox.Show("Receive Message Error"+ex.Message);
}
}
private void ChangeRtb(object obj, EventArgs e)
{
string s = System.Convert.ToString(obj);
this.rtbReceive.AppendText(s + Environment.NewLine);
}
private void btSend_Click(object sender, EventArgs e)
{
byte[] byteSend =
System.Text.Encoding.UTF8.GetBytes(this.tbSend.Text.ToCharArray());
try
{
this.sock.Send(byteSend);
}
catch
{
MessageBox.Show("Send Message Error");
}
}
private void btClose_Click(object sender, EventArgs e)
{
try
{
this.sock.Shutdown(SocketShutdown.Receive);
this.sock.Close();
Application.Exit();
}
catch
{
MessageBox.Show("Exit Error");
}
}
}
}
不解之处:
Client端红色标注语句:this.sock.Shutdown(SocketShutdown.Receive),如改成
this.sock.Shutdown(SocketShutdown.Both);或this.sock.Shutdown(SocketShutdown.Send);
则当点击Cloce按钮时,CPU使用率疯涨到100%,而使用this.sock.Shutdown(SocketShutdown.Receive);
或不调用Shutdown()方法则没有这个问题。难道客户端不应该用Shutdown()?