欢迎来到天天文库
浏览记录
ID:31630479
大小:61.76 KB
页数:17页
时间:2019-01-16
《cnet同步异步socket通讯和多线程总结2》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、服务端:usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading;Threadmythread;Socketsocket;//清理所有正在使用的资源。protectedoverridevoidDispose(booldisposing){try{socket.Close();〃释放资源mythread.Abort();〃中止线程}catch{}if(disposing){if(components!=null){components.
2、Dispose();}}base.Dispose(disposing);publicstaticIPAddressGetServerlP(){IPHostEntryieh=Dns.GetHostByName(Dns.GetHostName());returnieh.AddressList[O];}privatevoidBeginListen(){IPAddressServerlp=GetServerlP();IPEndPointiep=newIPEndPoint(Serverlp,8000);socket=newSocket(Add
3、ressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);byte[]byteMessage=newbyte[100];this.labell.Text=i即・ToString();socket.Bind(iep);//dowhile(true){try{socket.Listen(5);SocketnewSocket=socket.Accept();newSocket.Receive(byteMessage);stringsTime=DateTime.Now.ToSho
4、rtTimeString();stringmsg=sTime+”:"+”Messagefrom:”;msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);this」istBox1.Items.Add(msg);}catch(SocketExceptionex){this.labell.Text-+-=ex.ToString();}}//while(byteMessage!=null);}〃开始监听privatevoidbutt
5、on1_Click(objectsender,System.EventArgse){try{mythread=newThread(newThreadStart(BeginListen));mythread.Start();}catch(System.Exceptioner){MessageBox.Show(er.Message/f5LjJgn3MessageBoxButtons.OK,MessageBoxIcon.Stop);客户端:usingSystem.Net;usingSystem.Net.Sockets;usingSyste
6、m.Text;privatevoidbutton1_Click(objectsender,System.EventArgse){BeginSend();}privatevoidBeginSend(){stringip=this.txtip.Text;stringport=this.txtport.Text;IPAddressserverlp=IPAddress.Parse(ip);intserverPort=Convert.Tolnt32(port);IPEndPointiep=newIPEndPoint(serverlp5serv
7、erPort);byte[]byteMessage;//do//{Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);socket.Connect(iep);byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);socket.Send(byteMessage);socket.Shutdown(SocketShutdown.Both);socket.Close();//
8、while(byteMessage!=null);}基于TCP协议的发送和接收端TCP协议的接收端usingSystem.Net.Sockets;〃使用到TcpListen类usingSystem.Threading;〃使用到线程us
此文档下载收益归作者所有