一. TCP服务器的实现
1.创建套接字
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2.绑定本地终节点
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6065);
serverSocket.Bind(ep);
3.开启监听
serverSocket.Listen(0);
4.异步接收客户端连接请求
private void AsyncAccept(Socket socket)
{
socket.BeginAccept(asyncResult =>
{
Socket server = asyncResult.AsyncState as Socket;
//获取客户端套接字
Socket clientSocket = socket.EndAccept(asyncResult);
Debug.Log(string.Format("客户端{0}请求连接", clientSocket.RemoteEndPoint));
Client c = new Client(clientSocket);
clients.Add(c);
AsyncReceive(c);
AsyncAccept(server);
}, socket);
}
5.异步接收客户端信息
private void AsyncReceive(Client client)
{
try
{
client.clientSocket.BeginReceive(client.buffer, 0, client.buffer.Length, SocketFlags.None,
asyncResult =>
{
try
{
int length = client.clientSocket.EndReceive(asyncResult);
if (length > 0)
{
string message = Encoding.UTF8.GetString(client.buffer);
OnReceiveMessage(message);
AsyncReceive(client);
}
else
{
//客户端断开
OnClientDisconnect(client);
}
}
catch (SocketException e)
{
Debug.Log(e.Message.ToString());
if (client.clientSocket.Connected == false)
{
OnClientDisconnect(client);
}
}
}, client.clientSocket);
}
catch (Exception e)
{
Debug.Log(e.Message.ToString());
}
}
6.异步向客户端发送信息
private void AsyncSend(Client client, byte[] data)
{
if (client == null || data.Length == 0) return;
try
{
client.clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
{
int length = client.clientSocket.EndSend(asyncResult);
}, client.clientSocket);
}
catch (SocketException e)
{
Debug.Log(e.Message.ToString());
OnClientDisconnect(client);
}
}
二. TCP客户端的实现
1.创建套接字
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2.连接到服务器
clientSocket.BeginConnect(dataSourceServerEP, asyncResult =>
{
try
{
clientSocket.EndConnect(asyncResult);
Debug.Log(serviceName + ": 连接数据源服务器成功");
//接收消息
ReceiveMessageFromServer();
}
catch (SocketException e)
{
Debug.Log(e.Message.ToString());
ConnectToDataSourceServer(ip, port);
}
}, clientSocket);