1.Socket通信的基本流程
2.客户端
1 using System.Net.Sockets; 2 using System.Text; 3 using UnityEngine; 4 using UnityEngine.UI; 5 6 public class TestSocket : MonoBehaviour 7 { 8 private Socket socket; 9 public InputField inputField; 10 public Text text; 11 12 void Start() 13 { 14 //InterNetwork:使用IPv4 15 //InterNetworkV6:使用IPv6 16 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 17 } 18 19 public void TestConnect() 20 { 21 //Connect 22 socket.Connect("127.0.0.1", 8888); 23 } 24 25 public void TestSend() 26 { 27 //Send 28 byte[] writeBytes = Encoding.Default.GetBytes(inputField.text); 29 socket.Send(writeBytes); 30 31 //Receive 32 byte[] readBytes = new byte[1024]; 33 int count = socket.Receive(readBytes); 34 text.text = Encoding.Default.GetString(readBytes, 0, count); 35 36 //Close 37 socket.Close(); 38 } 39 }
3.服务端
1 using System; 2 using System.Net; 3 using System.Net.Sockets; 4 using System.Text; 5 6 namespace TestSocket 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 13 14 //Bind 15 IPAddress iPAddress = IPAddress.Parse("127.0.0.1"); 16 IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888); 17 socket.Bind(iPEndPoint); 18 19 //Listen 20 socket.Listen(0); 21 Console.WriteLine("Listen"); 22 23 while (true) 24 { 25 //Accept 26 Socket clientSocket = socket.Accept(); 27 Console.WriteLine("Accept"); 28 29 //Receive 30 byte[] readBytes = new byte[1024]; 31 int count = clientSocket.Receive(readBytes); 32 string readStr = Encoding.Default.GetString(readBytes, 0, count); 33 Console.WriteLine("Receive:" + readStr); 34 35 //Send 36 byte[] writeBytes = Encoding.Default.GetBytes(readStr); 37 clientSocket.Send(writeBytes); 38 } 39 } 40 } 41 }