【Unity3D】异步Socket通讯

时间:2022-09-26 12:20:08

1 前言

        同步 Socket 通讯 中的 Accept、Connect、Receive 等方法会阻塞当前线程,当前线程必须等待这些方法执行完,才会继续往下执行,用户需要另开线程执行这些耗时方法,否则会阻塞主线程,导致 UI 卡顿。

        异步 Socket 通讯中,通过 BeginAccept、EndAccept、BeginConnect、EndConnect、BeginReceive、EndReceive 等方法实现请求、连接、收消息等效果,这些方法通过回调(Callback)的方式实现异步通讯,并且不会阻塞主线程。

        在 BeginXXX(BeginAccept、BeginConnect、BeginReceive)方法的入参里,需要传递一个 Callback,当方法响应时(如收到请求、已连接上服务、收到消息),就会执行 Callback 里的内容,Callback 里通过 EndXXX(EndAccept、EndConnect、EndReceive)方法拿到响应信息,并进行相关数据处理。为避免在回调执行结束后程序也结束,从而不能继续收发消息,需要在回调的最后一行通过递归的方式执行 BeginXXX 方法,从而保证程序一直循环下去。

2 案例

        1)Socket 基本操作基类

        BaseSocket.cs

using System;

public abstract class BaseSocket {
	public virtual void OnAccept(IAsyncResult ar) {} // 服务端接收到连接的回调函数
	public virtual void OnConnect(IAsyncResult ar) {} // 客户端连接上服务端的回调函数
	public abstract void OnReceive(IAsyncResult ar); // 接收到消息的回调函数
	public abstract void Send(string msg); // 发送消息
}

        2)服务端

        AsyncSocketServer.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class AsyncSocketServer : BaseSocket {
	private Socket serverSocket; // 服务端通讯主机socket, 监听打进来的电话,并转接给客服
	private Socket kefuScoket; // 客服socket, 负责与客户一对一通讯
	private Action<string> msgCallback; // 消息回调
	private byte[] readBuff; // 收到消息的缓存

	public AsyncSocketServer(Action<string> callback) {
		msgCallback = callback;
		serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 12345);
		serverSocket.Bind(endPoint); // 绑定ip和端口
		serverSocket.Listen(1); // 监听电话连接, 设置最大客服人数, 如果是0就是无限个客服
		serverSocket.BeginAccept(OnAccept, serverSocket); // 接电话, 分配客服和客户进行一对一通信, 收到电话就会回调OnAccept方法
	}

	public override void OnAccept(IAsyncResult ar) { // 有客户连接上时, 回调此方法
		kefuScoket = serverSocket.EndAccept(ar);
		msgCallback("客服的本地端口是: " + kefuScoket.LocalEndPoint.ToString());
		msgCallback("客户的远程端口是: " + kefuScoket.RemoteEndPoint.ToString());
		readBuff = new byte[1024];
		BeginReceive();
		serverSocket.BeginAccept(OnAccept, serverSocket);
	}

	public override void OnReceive(IAsyncResult ar) { // 收到消息时, 回调此方法
		int count = serverSocket.EndReceive(ar);
		string msg = Encoding.UTF8.GetString(readBuff, 0, count);
		msgCallback("客户发来消息: " + msg);
		Array.Clear(readBuff, 0, readBuff.Length); // 清空缓存
		BeginReceive();
	}

	public override void Send(string msg) {
		byte[] buffer = Encoding.UTF8.GetBytes(msg);
		kefuScoket.Send(buffer);
	}

	private void BeginReceive() {
		kefuScoket.BeginReceive(
			readBuff, // 消息缓存
			0, readBuff.Length, // 消息接收的起始点以及长度
			SocketFlags.None, // 标志
			OnReceive, // 接收到消息的回调
			serverSocket // 状态
		);
	}

	~AsyncSocketServer() {
		kefuScoket.Close();
		serverSocket.Close();
	}
}

        3)客户端

        AsyncSocketClient.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class AsyncSocketClient : BaseSocket {
    private Socket clientSocket; // 客户端socket
    private Action<string> msgCallback; // 消息回调
	private byte[] readBuff; // 收到消息的缓存

    public AsyncSocketClient(Action<string> callback) {
        msgCallback = callback;
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
        clientSocket.BeginConnect(endPoint, OnConnect, clientSocket); // 连接服务器
    }

    public override void OnConnect(IAsyncResult ar) { // 连上服务器时, 回调此方法
        clientSocket.EndConnect(ar);
        readBuff = new byte[1024];
        BeginReceive();
    }

	public override void OnReceive(IAsyncResult ar) { // 收到消息时, 回调此方法
		Socket workingSocket = ar.AsyncState as Socket;
		int count = workingSocket.EndReceive(ar);
		string msg = Encoding.UTF8.GetString(readBuff, 0, count);
		msgCallback("客服发来消息: " + msg);
		Array.Clear(readBuff, 0, readBuff.Length); // 清空缓存
        BeginReceive();
	}

	public override void Send(string msg) {
        byte[] buffer = Encoding.UTF8.GetBytes(msg);
		clientSocket.Send(buffer);
	}

    private void BeginReceive() {
        clientSocket.BeginReceive(
			readBuff, // 消息缓存
			0, readBuff.Length, // 消息接收的起始点以及长度
			SocketFlags.None, // 标志
			OnReceive, // 接收到消息的回调
			clientSocket // 状态
		);
    }

	~AsyncSocketClient() {
		clientSocket.Close();
	}
}

        4)测试类

        AsyncSocketTest.cs

using UnityEngine;

public class AsyncSocketTest : MonoBehaviour {
	private BaseSocket socket; // 客户端/服务端socket
	private string sendText; // 发送的消息
	private string receiveText; // 接收的消息
	private bool isSideInited = false; // 是否已初始化端测
	private string sideTag = null; // 端测标记, 服务端/客户端

	private void Awake() {
		Application.runInBackground = true; // 支持后台运行
	}

	private void OnGUI() {
		InitSide();
		initSideView();
	}

	private void InitSide() { // 初始化端测
		if (!isSideInited) {
			CreateServer();
			CreateClient();
		}
	}

	private void CreateServer() { // 创建服务器
		if (GUILayout.Button("创建服务器")) {
			socket = new AsyncSocketServer((msg) => {
				receiveText += msg + "\n";
			});
			sideTag = "服务端";
			isSideInited = true;
		}
	}

	private void CreateClient() { // 创建客户端
		if (GUILayout.Button("创建客户端")) {
			socket = new AsyncSocketClient((msg) => {
				receiveText += msg + "\n";
			});
			sideTag = "客户端";
			isSideInited = true;
		}
	}

	private void initSideView() { // 初始化端测界面
		if (isSideInited) {
			GUILayout.Label(sideTag);
			sendText = GUILayout.TextField(sendText);
			if (GUILayout.Button("发送")) {
				socket.Send(sendText);
			}
			GUILayout.Label("接收到的消息: ");
			GUILayout.Label(receiveText);
		}
	}
}

        5)运行效果

【Unity3D】异步Socket通讯