Server:
byte[] readBuff;
string receiveStr;
Main():
{
serverSocket.Bind(IPEndPoint("127.0.0.1",8888));
serverSocket.Listen(0);
==服务器启动成功==
serverSocket.BeginAccept(AcceptCallback, serverSocket);
Console.ReadLine();
}
AcceptCallback(IAsyncResult ar):
{
serverSocket = ar.AsyncState as Socket;
clientSocket=serverSocket.EndAccept(ar);
==有一个客户端Accept==
clientSocket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, clientSocket);
serverSocket.BeginAccept(AcceptCallback, serverSocket);
}
ReceiveCallback(IAsyncResult ar):
{
Socket clientSocket = ar.AsyncState as Socket;
int count = clientSocket.EndReceive(ar);
if (count == 0)
{
clientSocket.Close();
Console.WriteLine("客户端断开连接");
return;
}
receiveStr=Encoding.UTF8.GetString(readBuff, 0, count);
=={receiveStr}==
clientSocket.BeginSend(Encoding.UTF8.GetBytes(receiveStr), 0, receiveStr.Length, 0, SendCallback, clientSocket);
clientSocket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, clientSocket);
}
SendCallback(IAsyncResult ar):
{
Socket clientSocket = ar.AsyncState as Socket;
clientSocket.EndSend(ar);
}
Client:
Socket socket;
byte[] readBuff;
string receiveStr;
Connect():
{
socket.BeginConnect("127.0.0.1",8888, ConnectCallback,socket);
}
ConnectCallback(IAsyncResult ar):
{
Socket socket = (Socket)ar.AsyncState;
socket.EndConnect(ar);
==连接成功==
socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
}
ReceiveCallback(IAsyncResult ar):
{
Socket socket = ar.AsyncState as Socket;
int count = socket.EndReceive(ar);
receiveStr = Encoding.UTF8.GetString(readBuff, 0, count);
socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);
}
Send():
{
string sendStr = InputField.text;
byte[] sendBytes =Encoding.UTF8.GetBytes(sendStr);
socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, socket);
}
SendCallback(IAsyncResult ar):
{
Socket socket = ar.AsyncState as Socket;
int count = socket.EndSend(ar);
==发送成功{count}==
}