在while循环中调用BeginRecieve()安全吗?while循环的条件是查看连接的套接字状态



我正在编写一个TCP/IP客户端,以便同时向连接的主机发送和接收数据。我的方法是连接到端点,并使用Socket.Connected属性在接收和发送之间循环(如果有任何数据要发送(。所有方法都是异步的,在适当的位置进行阻塞以从流中读取数据。在循环中多次调用BeginReceieve有什么问题吗?通过线程池看到这一点,底层运行时是否管理每次调用的后台线程数,或者我应该控制在所述while循环中何时开始接收调用?

调用BeginRecive((时不需要循环。BeginRecive((是一个异步方法,当您写入_socket.BeginReciv((时,它开始从连接的socket/Client异步接收数据。

例如:

public static void SetupRegisterServer()
{
Console.WriteLine("Setting up the Messesing Server!");
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 102));
_serverSocket.Listen(5); //Backlog is pending conditions can exists.    
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); //Async method BeginAccept if any client connect it will call the AcceptCallback method 
Console.WriteLine("Messesing Server running......");
}

AcceptCallback函数

public static void AcceptCallback(IAsyncResult ar)
{
var socket = _serverSocket.EndAccept(ar);//End accept 
Console.WriteLine("Client Connect To Messesings Server");
_clientSocketList.Add(socket);// add client to list 
// Start reciving from the connected client with callback function ReciveCallback
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReciveCallback), socket); 
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); //Here we again accepting clients.
}

接收回调方法

private static void ReciveCallback(IAsyncResult ar)
{
//here you will get the socket of the clint which send the data
Socket socket = (Socket)ar.AsyncState;
int recived = socket.EndReceive(ar);//recive == data.length
byte[] dataBuffer = new byte[recived];
Array.Copy(_buffer, dataBuffer, recived);
//Data send from client
string decodedText = Encoding.ASCII.GetString(dataBuffer);
//Start receiving again from the same client 
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReciveCallback), socket);
}

您也可以使用套接字。BeginSend((在接收回调中发送数据

最新更新