.NET中Socket编程的简单示例(2)

2008-02-22 09:37:28来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

{

MessageBox.Show("S:Close Socket Error" ex.Message);

}

}

}

}

== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

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()?

http://www.cnblogs.com/KissKnife/archive/2006/08/13/475707.html

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:.NET关于同步、异步及Socket

下一篇:.NET关于操作进程的简单示例