在下面的代码中,每个套接字都是为了表示客户端连接而创建的,我实例化 byte [] Buffer 来存储接收到的数据包缓冲区。
我的问题是:如何处理异步套接字,如果我有相同客户端的大量传入数据包, Buffer 在处理之前不会被覆盖,因为使用< em> BeginReceive (异步)?理论上使用 BeginReceive ,我可以接收多个套接字数据包,然后是另一个由不同线程管理的数据包。我错了吗?如果代码对此不安全,我如何优化它以防止?
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
namespace Server
{
public class ClientConnection
{
public Socket connectionSocket { get; set; }
private byte[] Buffer { get; set; }
public ClientConnection(Socket connectionSocket)
{
this.connectionSocket = connectionSocket;
this.Buffer = new byte[4096];
connectionSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), connectionSocket);
}
private void ReadCallback(IAsyncResult ar)
{
try
{
Socket socketReceive = (Socket)ar.AsyncState;
int bytesReceived = socketReceive.EndReceive(ar);
// Data was read from the client socket.
if (bytesReceived > 0)
{
//Console.WriteLine("Thread ID: " + Thread.CurrentThread.ManagedThreadId);
PacketReader packetReader = new PacketReader(Buffer);
connectionSocket.BeginReceive(Buffer, 0, Buffer.Length, 0, new AsyncCallback(ReadCallback), connectionSocket);
}
else
{
Disconnect();
Console.WriteLine("Connection closed from: " + connectionSocket.RemoteEndPoint.ToString());
}
}
catch (Exception ex)
{
Disconnect();
Console.WriteLine("Connection closed from: " + connectionSocket.RemoteEndPoint.ToString() + "Error: " + ex.Message);
}
}
public void Send(byte[] data)
{
try
{
connectionSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), connectionSocket);
}
catch (Exception ex)
{
Disconnect();
Console.WriteLine("Connection closed from: " + connectionSocket.RemoteEndPoint.ToString() + "Error: " + ex.Message);
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
Socket socketSend = (Socket)ar.AsyncState;
socketSend.EndSend(ar);
}
catch (Exception ex)
{
Disconnect();
Console.WriteLine("Connection closed from: " + connectionSocket.RemoteEndPoint.ToString() + "Error: " + ex.Message);
}
}
public void Disconnect()
{
connectionSocket.Close();
}
}
}