UDP服务端UdpServer
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using UnityEngine; 2 using System.Collections; 3 //引入库 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.Threading; 8 9 public class UdpServer:MonoBehaviour 10 { 11 //以下默认都是私有的成员 12 Socket socket; //目标socket 13 EndPoint clientEnd; //客户端 14 IPEndPoint ipEnd; //侦听端口 15 string recvStr; //接收的字符串 16 string sendStr; //发送的字符串 17 byte[] recvData=new byte[1024]; //接收的数据,必须为字节 18 byte[] sendData=new byte[1024]; //发送的数据,必须为字节 19 int recvLen; //接收的数据长度 20 Thread connectThread; //连接线程 21 22 23 //初始化 24 void InitSocket() 25 { 26 //定义侦听端口,侦听任何IP 27 ipEnd=new IPEndPoint(IPAddress.Any,8001); 28 //定义套接字类型,在主线程中定义 29 socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); 30 //服务端需要绑定ip 31 socket.Bind(ipEnd); 32 //定义客户端 33 IPEndPoint sender=new IPEndPoint(IPAddress.Any,0); 34 clientEnd=(EndPoint)sender; 35 print("waiting for UDP dgram"); 36 37 //开启一个线程连接,必须的,否则主线程卡死 38 connectThread=new Thread(new ThreadStart(SocketReceive)); 39 connectThread.Start(); 40 } 41 42 void SocketSend(string sendStr) 43 { 44 //清空发送缓存 45 sendData=new byte[1024]; 46 //数据类型转换 47 sendData=Encoding.ASCII.GetBytes(sendStr); 48 //发送给指定客户端 49 socket.SendTo(sendData,sendData.Length,SocketFlags.None,clientEnd); 50 } 51 52 //服务器接收 53 void SocketReceive() 54 { 55 //进入接收循环 56 while(true) 57 { 58 //对data清零 59 recvData=new byte[1024]; 60 //获取客户端,获取客户端数据,用引用给客户端赋值 61 recvLen=socket.ReceiveFrom(recvData,ref clientEnd); 62 print("message from: "+clientEnd.ToString()); //打印客户端信息 63 //输出接收到的数据 64 recvStr=Encoding.ASCII.GetString(recvData,0,recvLen); 65 print(recvStr); 66 //将接收到的数据经过处理再发送出去 67 sendStr="From Server: "+recvStr; 68 SocketSend(sendStr); 69 } 70 } 71 72 //连接关闭 73 void SocketQuit() 74 { 75 //关闭线程 76 if(connectThread!=null) 77 { 78 connectThread.Interrupt(); 79 connectThread.Abort(); 80 } 81 //最后关闭socket 82 if(socket!=null) 83 socket.Close(); 84 print("disconnect"); 85 } 86 87 // Use this for initialization 88 void Start() 89 { 90 InitSocket(); //在这里初始化server 91 } 92 93 94 // Update is called once per frame 95 void Update() 96 { 97 98 } 99 100 void OnApplicationQuit() 101 { 102 SocketQuit(); 103 } 104 }
UDP客户端UdpClient
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using UnityEngine; 2 using System.Collections; 3 //引入库 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.Threading; 8 9 public class UdpClient:MonoBehaviour 10 { 11 string editString="hello wolrd"; //编辑框文字 12 13 //以下默认都是私有的成员 14 Socket socket; //目标socket 15 EndPoint serverEnd; //服务端 16 IPEndPoint ipEnd; //服务端端口 17 string recvStr; //接收的字符串 18 string sendStr; //发送的字符串 19 byte[] recvData=new byte[1024]; //接收的数据,必须为字节 20 byte[] sendData=new byte[1024]; //发送的数据,必须为字节 21 int recvLen; //接收的数据长度 22 Thread connectThread; //连接线程 23 24 //初始化 25 void InitSocket() 26 { 27 //定义连接的服务器ip和端口,可以是本机ip,局域网,互联网 28 ipEnd=new IPEndPoint(IPAddress.Parse("127.0.0.1"),8001); 29 //定义套接字类型,在主线程中定义 30 socket=new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); 31 //定义服务端 32 IPEndPoint sender=new IPEndPoint(IPAddress.Any,0); 33 serverEnd=(EndPoint)sender; 34 print("waiting for sending UDP dgram"); 35 36 //建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息 37 SocketSend("hello"); 38 39 //开启一个线程连接,必须的,否则主线程卡死 40 connectThread=new Thread(new ThreadStart(SocketReceive)); 41 connectThread.Start(); 42 } 43 44 void SocketSend(string sendStr) 45 { 46 //清空发送缓存 47 sendData=new byte[1024]; 48 //数据类型转换 49 sendData=Encoding.ASCII.GetBytes(sendStr); 50 //发送给指定服务端 51 socket.SendTo(sendData,sendData.Length,SocketFlags.None,ipEnd); 52 } 53 54 //服务器接收 55 void SocketReceive() 56 { 57 //进入接收循环 58 while(true) 59 { 60 //对data清零 61 recvData=new byte[1024]; 62 //获取客户端,获取服务端端数据,用引用给服务端赋值,实际上服务端已经定义好并不需要赋值 63 recvLen=socket.ReceiveFrom(recvData,ref serverEnd); 64 print("message from: "+serverEnd.ToString()); //打印服务端信息 65 //输出接收到的数据 66 recvStr=Encoding.ASCII.GetString(recvData,0,recvLen); 67 print(recvStr); 68 } 69 } 70 71 //连接关闭 72 void SocketQuit() 73 { 74 //关闭线程 75 if(connectThread!=null) 76 { 77 connectThread.Interrupt(); 78 connectThread.Abort(); 79 } 80 //最后关闭socket 81 if(socket!=null) 82 socket.Close(); 83 } 84 85 // Use this for initialization 86 void Start() 87 { 88 InitSocket(); //在这里初始化 89 } 90 91 void OnGUI() 92 { 93 editString=GUI.TextField(new Rect(10,10,100,20),editString); 94 if(GUI.Button(new Rect(10,30,60,20),"send")) 95 SocketSend(editString); 96 } 97 98 // Update is called once per frame 99 void Update() 100 { 101 102 } 103 104 void OnApplicationQuit() 105 { 106 SocketQuit(); 107 } 108 }
TCP服务端TcpServer
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using UnityEngine; 2 using System.Collections; 3 //引入库 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.Threading; 8 9 public class TcpServer:MonoBehaviour 10 { 11 //以下默认都是私有的成员 12 Socket serverSocket; //服务器端socket 13 Socket clientSocket; //客户端socket 14 IPEndPoint ipEnd; //侦听端口 15 string recvStr; //接收的字符串 16 string sendStr; //发送的字符串 17 byte[] recvData=new byte[1024]; //接收的数据,必须为字节 18 byte[] sendData=new byte[1024]; //发送的数据,必须为字节 19 int recvLen; //接收的数据长度 20 Thread connectThread; //连接线程 21 22 //初始化 23 void InitSocket() 24 { 25 //定义侦听端口,侦听任何IP 26 ipEnd=new IPEndPoint(IPAddress.Any,5566); 27 //定义套接字类型,在主线程中定义 28 serverSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 29 //连接 30 serverSocket.Bind(ipEnd); 31 //开始侦听,最大10个连接 32 serverSocket.Listen(10); 33 34 35 36 //开启一个线程连接,必须的,否则主线程卡死 37 connectThread=new Thread(new ThreadStart(SocketReceive)); 38 connectThread.Start(); 39 } 40 41 //连接 42 void SocketConnet() 43 { 44 if(clientSocket!=null) 45 clientSocket.Close(); 46 //控制台输出侦听状态 47 print("Waiting for a client"); 48 //一旦接受连接,创建一个客户端 49 clientSocket=serverSocket.Accept(); 50 //获取客户端的IP和端口 51 IPEndPoint ipEndClient=(IPEndPoint)clientSocket.RemoteEndPoint; 52 //输出客户端的IP和端口 53 print("Connect with "+ipEndClient.Address.ToString()+":"+ipEndClient.Port.ToString()); 54 //连接成功则发送数据 55 sendStr="Welcome to my server"; 56 SocketSend(sendStr); 57 } 58 59 void SocketSend(string sendStr) 60 { 61 //清空发送缓存 62 sendData=new byte[1024]; 63 //数据类型转换 64 sendData=Encoding.ASCII.GetBytes(sendStr); 65 //发送 66 clientSocket.Send(sendData,sendData.Length,SocketFlags.None); 67 } 68 69 //服务器接收 70 void SocketReceive() 71 { 72 //连接 73 SocketConnet(); 74 //进入接收循环 75 while(true) 76 { 77 //对data清零 78 recvData=new byte[1024]; 79 //获取收到的数据的长度 80 recvLen=clientSocket.Receive(recvData); 81 //如果收到的数据长度为0,则重连并进入下一个循环 82 if(recvLen==0) 83 { 84 SocketConnet(); 85 continue; 86 } 87 //输出接收到的数据 88 recvStr=Encoding.ASCII.GetString(recvData,0,recvLen); 89 print(recvStr); 90 //将接收到的数据经过处理再发送出去 91 sendStr="From Server: "+recvStr; 92 SocketSend(sendStr); 93 } 94 } 95 96 //连接关闭 97 void SocketQuit() 98 { 99 //先关闭客户端 100 if(clientSocket!=null) 101 clientSocket.Close(); 102 //再关闭线程 103 if(connectThread!=null) 104 { 105 connectThread.Interrupt(); 106 connectThread.Abort(); 107 } 108 //最后关闭服务器 109 serverSocket.Close(); 110 print("diconnect"); 111 } 112 113 // Use this for initialization 114 void Start() 115 { 116 InitSocket(); //在这里初始化server 117 } 118 119 120 // Update is called once per frame 121 void Update() 122 { 123 124 } 125 126 void OnApplicationQuit() 127 { 128 SocketQuit(); 129 } 130 }
TCP客户端TcpClient
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using UnityEngine; 2 using System.Collections; 3 //引入库 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Text; 7 using System.Threading; 8 9 public class TcpClient:MonoBehaviour 10 { 11 string editString="hello wolrd"; //编辑框文字 12 13 Socket serverSocket; //服务器端socket 14 IPAddress ip; //主机ip 15 IPEndPoint ipEnd; 16 string recvStr; //接收的字符串 17 string sendStr; //发送的字符串 18 byte[] recvData=new byte[1024]; //接收的数据,必须为字节 19 byte[] sendData=new byte[1024]; //发送的数据,必须为字节 20 int recvLen; //接收的数据长度 21 Thread connectThread; //连接线程 22 23 //初始化 24 void InitSocket() 25 { 26 //定义服务器的IP和端口,端口与服务器对应 27 ip=IPAddress.Parse("127.0.0.1"); //可以是局域网或互联网ip,此处是本机 28 ipEnd=new IPEndPoint(ip,5566); 29 30 31 //开启一个线程连接,必须的,否则主线程卡死 32 connectThread=new Thread(new ThreadStart(SocketReceive)); 33 connectThread.Start(); 34 } 35 36 void SocketConnet() 37 { 38 if(serverSocket!=null) 39 serverSocket.Close(); 40 //定义套接字类型,必须在子线程中定义 41 serverSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 42 print("ready to connect"); 43 //连接 44 serverSocket.Connect(ipEnd); 45 46 //输出初次连接收到的字符串 47 recvLen=serverSocket.Receive(recvData); 48 recvStr=Encoding.ASCII.GetString(recvData,0,recvLen); 49 print(recvStr); 50 } 51 52 void SocketSend(string sendStr) 53 { 54 //清空发送缓存 55 sendData=new byte[1024]; 56 //数据类型转换 57 sendData=Encoding.ASCII.GetBytes(sendStr); 58 //发送 59 serverSocket.Send(sendData,sendData.Length,SocketFlags.None); 60 } 61 62 void SocketReceive() 63 { 64 SocketConnet(); 65 //不断接收服务器发来的数据 66 while(true) 67 { 68 recvData=new byte[1024]; 69 recvLen=serverSocket.Receive(recvData); 70 if(recvLen==0) 71 { 72 SocketConnet(); 73 continue; 74 } 75 recvStr=Encoding.ASCII.GetString(recvData,0,recvLen); 76 print(recvStr); 77 } 78 } 79 80 void SocketQuit() 81 { 82 //关闭线程 83 if(connectThread!=null) 84 { 85 connectThread.Interrupt(); 86 connectThread.Abort(); 87 } 88 //最后关闭服务器 89 if(serverSocket!=null) 90 serverSocket.Close(); 91 print("diconnect"); 92 } 93 94 // Use this for initialization 95 void Start() 96 { 97 InitSocket(); 98 } 99 100 void OnGUI() 101 { 102 editString=GUI.TextField(new Rect(10,10,100,20),editString); 103 if(GUI.Button(new Rect(10,30,60,20),"send")) 104 SocketSend(editString); 105 } 106 107 // Update is called once per frame 108 void Update() 109 { 110 111 } 112 113 //程序退出则关闭连接 114 void OnApplicationQuit() 115 { 116 SocketQuit(); 117 } 118 }