Unity中Socket的使用

Unity中Socket的使用

  • Socket的使用
  • 客户端逻辑
    • 脚步TcpSocket.cs
    • 测试脚本
  • 服务器端数据
    • 控制客户端的Socke的脚本ClientSocket.cs
    • 服务器Socket的脚本ServerSocket.cs
    • 测试脚本

Socket的使用

在unity中使用Socket连接服务器进行消息发送和接收

客户端逻辑

脚步TcpSocket.cs


public class TcpSocket
{
	private Socket mSocket;
	private byte[] mData;
	private int mOffect;
	/// 
	///	一次性接收数据的最大字节
	/// 
	private int mSize = 1024*1024*1;
	
	
	public TcpSocket(string varIp,int varPort)
	{
		IPEndPoint point = new IPEndPoint(IPAddress.Parse(varIp), varPort);
		mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		mSocket.BeginConnect(point, Connect, null);
	}
	~TcpSocket()
	{
		CloseConnect();
	}
	/// 
	///	连接服务器结果
	/// 
	private void Connect(IAsyncResult result)
	{
		if(result.IsCompleted)
		{
			//连接成功
			mData = new byte[mSize];
			//开启数据接收的异步监听
			mSocket.BeginReceive(mData, mOffect, mSize - mOffect, SocketFlags.None, Receive, null);
		}
		else
		{
			//连接失败
		}
	}
	/// 
	///	接收到服务器数据
	/// 
	private void Receive(IAsyncResult result)
	{
		//结束当前监听进行数据处理
		int size = mSocket.EndReceive(result, out SocketError error);
		if(error == 0)
		{
			//接收数据成功
			if(size != 0)
			{
				//当数据大小不为0时进行数据内容处理
				//此处理方式为测试数据
				byte[] bytes = new byte[size + mOffect];
				Array.Copy(mData, 0, bytes, 0, size + mOffect);
				string message = Encoding.UTF8.GetString(bytes);
				
				Debug.LogError(message);
			}
			//开启数据接收的异步监听
			mSocket.BeginReceive(mData, mOffect, mSize - mOffect, SocketFlags.None, Receive, null);
		}
		else
		{
			//接收数据发生错误-自动断开连接
			CloseConnect();
		}
	}
	/// 
	///	发生数据给服务器
	/// 
	public void Send(byte[] bytes)
	{
		try
		{
			mSocket.Send(bytes);
		}
		catch(Exception exp)
		{
			Debug.LogError(exp.Message);
			//发生数据异常-自动断开连接
			CloseConnect();
		}
	}
	/// 
	///	关闭服务器连接
	/// 
	public void CloseConnect()
	{
		if(mSocket.Connected)
		{
			mSocket.Close();
		}
	}
}

测试脚本


public void Client:MonoBehaviour
{
	TcpSocket mTcpSocket;

	public void Init()
	{
		mTcpSocket = new TcpSocket("127.0.0.1", 4488);
	}
	public void Send()
	{
		mTcpSocket.Send(Encoding.UTF8.GetBytes("测试数据"));
	}
	
}

服务器端数据

控制客户端的Socke的脚本ClientSocket.cs


public class ClientSocket
{
 	Socket mSocket;
 	byte[] mData;
 	int mOffect;
	/// 
	///	一次性接收数据的最大字节
	/// 
 	int mSize = 1024*1024*1;
	
	Action<ClientSocket> CloseCallBack;
	
	public ClientSocket(Socket varSocket, Action<ClientSocket> action)
	{
		CloseCallBack = action;
		mSocket = varSocket;
		//获取当前连接的客户端的IP和端口
		IPEndPoint  IPEnd = mSocket.RemoteEndPoint as IPEndPoint;
		//IP地址
 		string IP = IPEnd.Address.ToString();
 		//Port端口
 		int Port = IPEnd.Port;
 		
		mData = new byte[mSize];
		//开启数据接口监听
		mSocket.BeginReceive(mData, mOffect, mSize - mOffect, SocketFlags.None, Receive, null);
	}
	private void Receive(IAsyncResult result)
	{
		//结束当前监听进行数据处理
		int size = mSocket.EndReceive(result, out SocketError error);
		if(error == 0)
		{
			//接收数据成功
			if(size != 0)
			{
				//当数据大小不为0时进行数据内容处理
				byte[] bytes = new byte[size + mOffect];
				Array.Copy(mData, 0, bytes, 0, size + mOffect);
				string message = Encoding.UTF8.GetString(bytes);
				
				Debug.LogError(message);
			}
			//开启数据接收的异步监听
			mSocket.BeginReceive(mData, mOffect, mSize - mOffect, SocketFlags.None, Receive, null);
		}
		else
		{
			//接收数据发生错误-自动断开连接
			CloseConnect();
		}
	}
	
	/// 
	///	发生数据给指定客服端
	/// 
	public void Send(byte[] bytes)
	{
		try
		{
			mSocket.Send(bytes);
		}
		catch(Exception exp)
		{
			//发生数据异常-自动断开连接
			CloseConnect();
		}
	}
	/// 
	///	关闭指定客服端连接
	/// 
	public void CloseConnect()
	{
		if(mSocket.Connected)
		{
			CloseCallBack(this);
			mSocket.Close();
		}
	}
}

服务器Socket的脚本ServerSocket.cs


public class ServerSocket
{
	Socket mSocket;
	List<ClientSocket> mClients = new List<ClientSocket>();
	
	/// 
	///	启动服务器
	/// 
	///	服务器的IP
	///	服务器的端口
	public ServerSocket(string varIP, int varPort)
	{
		mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		mSocket.Bind(new IPEndPoint(IPAddress.Parse(varIP), varPort));
		//开启连接监听并设置最大连接数
		mSocket.Listen(100);
		//开启连接响应监听
		mSocket.BeginAccept(Accept, null);
	}
	private void Accept(IAsyncResult result)
	{
		//收到连接后结束连接监听并获取当前连接的客户端Socket
		Socket TempClient = mSocket.EndAccept(result);
		
		 ClientSocket client = new ClientSocket(TempClient, CloseClient);
		 //将连接的客户端记录下来
		 mClients.Add(client);
		 //重新开启客户端的连接监听
		mSocket.BeginAccept(Accept, null);
	}
	/// 
	///	关闭客户端连接
	/// 
	private void CloseClient(ClientSocket  client)
	{
		if(mClients.Contains(client))
		{
			mClients.Remove(client);
		}
	}
}


测试脚本


class Program
{
	static void Main(string[] args)
	{
		ServerSocket socket = new ServerSocket("127.0.0.1", 4488);
		Console.Read();
	}
}

你可能感兴趣的:(Unity,unity)