通常的Socket都是通过多线程的方式来实现的,多线程需要确保线程安全,而且代码量也会相对多一些,由于之前已经实现了Unity的协程功能,现在就可以通过协程来实现单线程的Socket了。
首先,封装一下C#的Socket。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using FirBase;
namespace NxNetwork
{
public class NxSocket
{
private Socket _socket;
public NxSocket()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public bool Connect(string ip, int port)
{
return Connect(new IPEndPoint(IPAddress.Parse(ip), port));
}
public bool Connect(IPEndPoint ipPoint)
{
bool connected = false;
try
{
FirLog.v(this, "连接服务器:" + ipPoint.Address.ToString());
_socket.NoDelay = true;
_socket.Connect(ipPoint);
_socket.Blocking = false;
connected = true;
}
catch(Exception ex)
{
FirLog.v(this, "连接出现异常:" + ex.Message);
}
return connected;
}
public bool Disconnect()
{
bool success = false;
try
{
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
success = true;
}
catch (Except

本文介绍如何在Unity中使用协程实现单线程Socket通信,避免多线程带来的线程安全问题。通过封装C# Socket并设置为非阻塞模式,结合Unity的协程功能,简化了Socket的接收数据过程。示例代码中展示了如何启动NetworkManager,创建消息处理类,并进行消息注册和接收。
最低0.47元/天 解锁文章
1276





