首先创建一个服务器
using UnityEngine; using System.Collections; using System.Net.Sockets; using System.Net; using System.Threading; //引入线程的包 public class ServerSocket : MonoBehaviour { private Socket serverSocket; void Start() { //1使用socket创建一个对象 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); //2创建一个IpEndPoint对象(加入Ip地址) IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2333); serverSocket.Bind(endPoint); serverSocket.Listen(10); //3设置缓冲区的大小, 进行监听 ThreadStart s = new ThreadStart(X); //创建一个线程 Thread t = new Thread(s); t.Start(); } void Update () { } private void X() { //4使用Accept()方法 Socket clientSocket = serverSocket.Accept(); //5接收使用Receive()方法接受客户端消息 byte[] receiveBuffer = new byte[1024]; //缓存的大小 int count = clientSocket.Receive(receiveBuffer); string receiveStr = System.Text.Encoding.UTF8.GetString(receiveBuffer); //把byte转化为字符串 print(receiveStr); //6发送数据 string str = "老王你好"; byte[] sendBuffer = new byte[1024]; sendBuffer = System.Text.Encoding.UTF8.GetBytes(str); clientSocket.Send(sendBuffer); clientSocket.Close(); } } 在家建立一个客户端
using UnityEngine; using System.Collections; using System.Net.Sockets; using System.Net; using System.Threading; public class ClientSocket : MonoBehaviour { private Socket clientSocket; void Start () { } void Update () { if(Input.GetKeyDown(KeyCode.P)) //按下P键,连接服务器 { //1.创建客户端(Socket) clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 2. 使用 Connect() 方法连接服务器 clientSocket.Connect("127.0.0.1", 2333); string str = "你好, 我是老王!"; byte[] sendBuffer = System.Text.Encoding.UTF8.GetBytes(str); // 3. 使用 Send() 方法向客户端发送消息 clientSocket.Send(sendBuffer); ThreadStart s = new ThreadStart(X); Thread t = new Thread(s); t.Start(); } } private void X() { byte[] receiveBuffer = new byte[1024]; // 4. 使用 Receive() 方法接收客户端消息 clientSocket.Receive(receiveBuffer); string receiveStr = System.Text.Encoding.UTF8.GetString(receiveBuffer); print(receiveStr); // 5. 使用 Close() 方法断开连接 clientSocket.Close(); } }
时间: 2024-10-11 01:47:50