Socket基础之服务端(基于UDP)

来源:互联网 发布:单片机plc培训 编辑:程序博客网 时间:2024/05/29 06:43
 
view plaincopy to clipboardprint?
  1. //设置“终结点”   
  2. IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 8001);  
  3. //创建与客户机连接的套接字(基于UDP协议无需侦听Socket)  
  4. Socket ConnSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
  5. //绑定网络地址   
  6. ConnSocket.Bind(ipe);  
  7.   
  8. Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());  
  9. //等待客户机连接   
  10. Console.WriteLine("Waiting for a client");  
  11.   
  12. IPEndPoint client = new IPEndPoint(IPAddress.Any, 0);  
  13. //客户机终结点   
  14. EndPoint Remote = (EndPoint)(client);  
  15. byte[] data = new byte[1024];  
  16. //从客户机接收信息,并将信息保存到数据缓冲区data   
  17. int recv = ConnSocket.ReceiveFrom(data, ref Remote);  
  18. //将接收的信息(客户机ip及端口号和文本信息)打印出来   
  19. Console.WriteLine("Message received from {0}: ", Remote.ToString());  
  20. Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));  
  21.   
  22. //客户机连接成功后,发送欢迎信息   
  23. string welcome = "Server Message:Welcome!!!";  
  24. //字符串与字节数组相互转换   
  25. data = Encoding.ASCII.GetBytes(welcome);  
  26. //给客户机发送信息   
  27. ConnSocket.SendTo(data, data.Length, SocketFlags.None, Remote);  
  28. while (true//时刻准备接收从客户机发回的信息  
  29. {  
  30.     data = new byte[1024];  
  31.     recv = ConnSocket.ReceiveFrom(data, ref Remote);  
  32.     if (Encoding.ASCII.GetString(data, 0, recv) == "exit")  
  33.     {  
  34.         Console.WriteLine("Client has been exit from the connection.");  
  35.         //给客户机发送一条"exit"消息表示欲关闭连接  
  36.         welcome = "Server exit!!!";  
  37.         data = Encoding.ASCII.GetBytes(welcome);  
  38.         ConnSocket.SendTo(data, data.Length, SocketFlags.None, Remote);  
  39.         ConnSocket.Close();  
  40.         break;  
  41.     }  
  42.     else  
  43.     {  
  44.         Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));  
  45.         //告知客户机当前信息已成功接收   
  46.         welcome = "Server has been received successfully!!!";  
  47.         data = Encoding.ASCII.GetBytes(welcome);  
  48.         ConnSocket.SendTo(data, data.Length, SocketFlags.None, Remote);  
  49.     }  
  50. }  
原创粉丝点击