新建一个Unity项目新建脚本编写客户端
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;public class Client : MonoBehaviour
{private Socket socket;//定义用来存消息的容器private byte[] buffer = new byte[1024];// Start is called before the first frame updatevoid Start(){//参数: IPV4协议, 套接字的传输类型(流式传输), socket传输协议(TCP)socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream ,ProtocolType.Tcp); //连接服务器: 服务器IP, 服务器端口号socket.Connect("127.0.0.1", 6666); //连接完成//连接成功调用接收方法异步接收消息StartReceive();//连接成功发送消息Send();}//接收消息void StartReceive(){socket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,ReceiveCallback,null);}//接收消息的回调方法(作为参数传递的函数)void ReceiveCallback(IAsyncResult iar){//接收返回消息长度int len = socket.EndReceive(iar);//接收为0代表终止连接if (len == 0){return;}//解析bufferstring str = Encoding.UTF8.GetString(buffer, 0, len);Debug.Log(str);//解析完在执行接收方法 StartReceive();}void Send(){socket.Send(Encoding.UTF8.GetBytes("服务器你好,我是客户端!"));}// Update is called once per framevoid Update(){}
}
创建一个空物体挂载客户端脚本
新建一个窗体应用编写服务端
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;public class Program
{private static Socket socket;private static byte[] buffer = new byte[1024];static void Main(string[] args){//初始化socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//绑定socket.Bind(new IPEndPoint(IPAddress.Any, 6666));//监听: 挂起的连接队列最大长度 —— 同时处理连接请求的最大数,超出最大数会排队等待socket.Listen(0);StartAccept();Console.Read(); //阻塞住让程序不会结束}//开始应答static void StartAccept(){//开始异步应答连接 参数: 回调函数,objectsocket.BeginAccept(AcceptCallback, null);}static void AcceptCallback(IAsyncResult iar){//异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。Socket client = socket.EndAccept(iar);//开始接收StartReceive(client);//重新开始应答StartAccept();}//接收消息static void StartReceive(Socket client){//开始从连接的 Socket 中异步接收数据client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, client);}//回调函数static void ReceiveCallback(IAsyncResult iar){Socket client = iar.AsyncState as Socket;//结束接收返回消息长度int len = client.EndReceive(iar);//接收为0代表终止连接if (len == 0){return;}//解析bufferstring str = Encoding.UTF8.GetString(buffer, 0, len);Console.WriteLine(str);//解析完在执行接收方法 StartReceive(client);}
}
先运行服务端然后运行客户端