.NET中Socket编程的简单示例(2)
2008-02-22 09:37:28来源:互联网 阅读 ()
{
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关于操作进程的简单示例
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
