0
如何停止向客戶端發送消息,而客戶端不從服務器讀取消息。爲了更好地理解這意味着什麼,考慮一種情況,即客戶端在長時間內不會調用Read,並且服務器停止向該客戶端發送消息。 Server.cs從客戶端接收消息,發送給所有的客戶套接字多客戶端一臺服務器
private static void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
current.Close();
clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
Console.WriteLine("Received Text: " + text);
buffQueue.Enqueue(text);
current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
foreach (var client in clientSockets)
{
foreach (var msg in buffQueue)
{
Sendata(client, text);
}
}
}
static void Sendata(Socket socket, string noidung)
{
byte[] data = Encoding.ASCII.GetBytes(noidung);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
}
private static void SendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
Client.cs
public void ReceiveMessage(IAsyncResult ar)
{
Random rnd = new Random();
Socket socket = (Socket)ar.AsyncState;
int received = socket.EndReceive(ar);
byte[] dataBuf = new byte[received];
Array.Copy(receivedBuf, dataBuf, received);
string msg = Encoding.ASCII.GetString(dataBuf);
Console.WriteLine("> " + msg + '\n');
ClientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None,
new AsyncCallback(ReceiveMessage), ClientSocket);
}