一个最简单的c# Socket 服务器端实例 异步.docx
文本预览下载声明
1.简单服务器端/*using System.Data;using System.Net.Sockets;using System.Net;using System.Threading;private static int port = %%2;private static Thread thThreadRead;private static TcpListenerTcpListen;private static boolbListener = true;private static Socket stRead;*/private static void Listen(){ try {TcpListen = new TcpListener(port);TcpListen.Start();stRead = TcpListen.AcceptSocket();EndPointtempRemoteEP = stRead.RemoteEndPoint;IPEndPointtempRemoteIP = (IPEndPoint)tempRemoteEP;IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address); string sHostName = host.HostName; while (bListener) {stRead.Send(Encoding.ASCII.GetBytes(%%1)); string sTime = DateTime.Now.ToShortTimeString(); Byte[] byRead = new Byte[1024];intiRead = stRead.ReceiveFrom(byRead, ref tempRemoteEP); Byte[] byText = new Byte[iRead];Array.Copy(byRead, 0, byText, 0, iRead); string line = System.Text.Encoding.Default.GetString(byRead); } } catch (System.Security.SecurityException) { //监听失败 }}thThreadRead = new Thread(new ThreadStart(Listen));thThreadRead.Start();2.简单客户端/*using System.Data;using System.Net.Sockets;using System.Net;private static IPEndPointdateTimeHost;*/string hostIPString=%%1;string hostPortString=%%2;IPAddresshostIP=IPAddress.Parse(hostIPString);dateTimeHost=new IPEndPoint(hostIP,Int32.Parse(hostPortString));Socket conn=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);conn.Connect(dateTimeHost);int bytes=0;Byte[] RecvBytes=new Byte[256];bytes=conn.Receive(RecvBytes,RecvBytes.Length,0);string RecvString=Encoding.ASCII.GetString(RecvBytes,0,bytes);Console.WriteLine(RecvString);conn.Shutdown(SocketShutdown.Both);conn.Close();3.获得本机IP//using System.Net;IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;string %%1=null;for (inti = 0; i addressList.Length; i++){ %%1 += addressList[i].ToString();}5.点对点通信/*using System.Data;using System.Net.Sockets;using System.Net;using System.Threading;*/Thread th;TcpListener tpListen1;boollistenerRu
显示全部