Unity Socket UDP

来源:互联网 发布:linux怎么设置搜狗 编辑:程序博客网 时间:2024/05/16 08:55
[csharp] view plain copy
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using System.Net.Sockets;  
  4. using System.Net;  
  5. using System.Threading;  
  6. using System.Text;  
  7.   
  8.   
  9. public class SocketUDPServer  
  10. {  
  11.     private string ip = "127.0.0.1";  
  12.     private int port = 5690;  
  13.     private Socket socket;  
  14.     private static SocketUDPServer socketServer;  
  15.     public List<string> listMessage = new List<string>();  
  16.   
  17.     public static SocketUDPServer getInstance()  
  18.     {  
  19.         if (socketServer == null)  
  20.         {  
  21.             socketServer = new SocketUDPServer();  
  22.             socketServer.Init();  
  23.         }  
  24.         return socketServer;  
  25.     }  
  26.   
  27.     private void Init()  
  28.     {  
  29.         IPAddress ipAddress = IPAddress.Parse(ip);  
  30.         IPEndPoint IPE = new IPEndPoint(ipAddress,port);  
  31.         //Udp搭配SocketType.Dgram   Tcp搭配SocketType.Stream  
  32.         socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);  
  33.         socket.Bind(IPE);  
  34.         Thread threadReceive = new Thread(new ThreadStart(ReceiveMessage));  
  35.         threadReceive.Start();  
  36.     }  
  37.     private void ReceiveMessage()  
  38.     {  
  39.         while (true)  
  40.         {  
  41.             byte[] buff = new byte[1024];  
  42.             int iBytes = socket.Receive(buff, SocketFlags.None);  
  43.             if (iBytes <= 0)  
  44.                 break;  
  45.             string strGetMessage = Encoding.ASCII.GetString(buff, 0, iBytes);  
  46.             listMessage.Add(strGetMessage);  
  47.         }  
  48.     }  
  49.     public void  Close()  
  50.     {  
  51.         if(socket!=null)  
  52.             socket.Close();  
  53.     }  
  54.      
  55.   
  56. }  
原创粉丝点击