文档详情

DotNET(C#) Socket基本编程.doc

发布:2017-08-17约6.87千字共20页下载文档
文本预览下载声明
DotNET(C#) Socket基本编程 Socket基本编程 服务端: using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; Thread mythread ; Socket socket; // 清理所有正在使用的资源。 protected override void Dispose( bool disposing ) { try   {       socket.Close();//释放资源    mythread.Abort ( ) ;//中止线程   }   catch{ } if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } public static IPAddress GetServerIP() { IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName()); return ieh.AddressList[0]; } private void BeginListen() { IPAddress ServerIp=GetServerIP(); IPEndPoint iep=new IPEndPoint(ServerIp,8000); socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); byte[] byteMessage=new byte[100]; this.label1.Text=iep.ToString(); socket.Bind(iep); // do while(true) { try { socket.Listen(5); Socket newSocket=socket.Accept(); newSocket.Receive(byteMessage); string sTime = DateTime.Now.ToShortTimeString ( ) ; string msg=sTime+:+Message from:; msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage); this.listBox1.Items.Add(msg); } catch(SocketException ex) { this.label1.Text+=ex.ToString(); } } // while(byteMessage!=null); } //开始监听 private void button1_Click(object sender, System.EventArgs e) { try { mythread = new Thread(new ThreadStart(BeginListen)); mythread.Start(); } catch(System.Exception er) { MessageBox.Show(er.Message,完成,MessageBoxButtons.OK,MessageBoxIcon.Stop); } } 客户端: using System.Net; using System.Net.Sockets; using System.Text; private void button1_Click(object sender, System.EventArgs e) { BeginSend(); } private void BeginSend() { string ip=this.txtip.Text; string port=this.txtport.Text; IPAddress serverIp=IPAddr
显示全部
相似文档