欢迎来到天天文库
浏览记录
ID:41032248
大小:21.91 KB
页数:8页
时间:2019-08-14
《c# socket 编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、/Socket基本编程//服务端:usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading; Threadmythread;Socketsocket;//清理所有正在使用的资源。PRotectedoverridevoidDispose(booldisposing){try { socket.Close();//释放资源 mythread.Abort();//中止线程 } catch{} if(disposing
2、){if(components!=null){components.Dispose();}}base.Dispose(disposing);}publicstatic ipAddressGetServerIP(){IPHostEntryieh=Dns.GetHostByName(Dns.GetHostName());returnieh.AddressList[0];}privatevoidBeginListen(){IPAddressServerIp=GetServerIP();IPEndPointiep=newIP
3、EndPoint(ServerIp,8000);socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); byte[]byteMessage=newbyte[100];this.label1.Text=iep.ToString();socket.Bind(iep);//dowhile(true){try{socket.Listen(5);SocketnewSocket=socket.Accept();newSock
4、et.Receive(byteMessage); stringsTime=DateTime.Now.ToShortTimeString();stringmsg=sTime+":"+"Messagefrom:";msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);this.listBox1.Items.Add(msg); }catch(SocketExceptionex){this.label1.Text+=e
5、x.ToString();}}//while(byteMessage!=null);}//开始监听privatevoidbutton1_Click(objectsender,System.EventArgse){try{mythread=newThread(newThreadStart(BeginListen));mythread.Start(); }catch(System.Exceptioner){MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,Messa
6、geBoxIcon.Stop);}} //客户端: usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text; privatevoidbutton1_Click(objectsender,System.EventArgse){BeginSend();}privatevoidBeginSend(){stringip=this.txtip.Text;stringport=this.txtport.Text; IPAddressserverIp=IPAddress.
7、Parse(ip);intserverPort=Convert.ToInt32(port);IPEndPointiep=newIPEndPoint(serverIp,serverPort);byte[]byteMessage;//do//{Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);socket.Connect(iep); byteMessage=Encoding.ASCII.GetByte
8、s(textBox1.Text);socket.Send(byteMessage);socket.Shutdown(SocketShutdown.Both);socket.Close();//}//while(byteMessage!=null);} 基于TCP协议的发送和接收端 TCP协议的接收端 usingSystem.Net.Socket
此文档下载收益归作者所有