通常的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;
}
ca