C#中Socket通信用法实例详解

2019-12-26 13:33:16丽君

易采站长站为您分析C#中Socket通信用法,以实例形式较为详细的分析了UDP及TCP两种通信方式的具体实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#中Socket通信用法。。具体如下:

一、UDP方式:

服务器端代码:

 

 
  1. static void Main(string[] args)  { 
  2. int recv;  byte[] data = new byte[1024]; 
  3. IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点  Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket 
  4. newsock.Bind(ipep);//Socket与本地的一个终结点相关联  Console.WriteLine("Waiting for a client.."); 
  5. IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址  EndPoint Remote = (EndPoint)(sender);// 
  6. recv = newsock.ReceiveFrom(data, ref Remote);//接受数据   Console.WriteLine("Message received from{0}:", Remote.ToString()); 
  7. Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));  string welcome = "Welcome to my test server!"; 
  8. data = Encoding.ASCII.GetBytes(welcome);  newsock.SendTo(data, data.Length, SocketFlags.None, Remote); 
  9. while (true)  { 
  10. data = new byte[1024];  recv = newsock.ReceiveFrom(data, ref Remote); 
  11. Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));  newsock.SendTo(data, recv, SocketFlags.None, Remote); 
  12. }  }