C# 接收数据的问题
当我从客户端快速多次发送数据时,我不会在服务器中单独接收这些数据。我将它们作为一个大数据突发来接收。我需要为每个收到的数据发送回复。但我做不到,因为这些数据会合并成一个大突发。如何为每个收到的数据发送回复? 服务器端回调方法代码如下:
private void RecieveCallback(IAsyncResult asyncResult)
{
ConnectionInfo connection = (ConnectionInfo)asyncResult.AsyncState;
try
{
int bytesRead = connection.Socket.EndReceive(asyncResult);
if (bytesRead > 0)
{
for (int i = 0; i < bytesRead; i++)
connection.FullBufferReceive.Add(connection.BufferReceive[i]);
if (bytesRead == connection.BufferReceive.Length)
{
connection.Socket.BeginReceive(connection.BufferReceive, 0, connection.BufferReceive.Length, 0,
new AsyncCallback(RecieveCallback), connection);
Console.WriteLine("Bytes recieved -- " + bytesRead + " by " + connection.Id);
}
else
{
Console.WriteLine("Bytes recieved " + bytesRead + " by " + connection.Id);
_serverController.StartProcess(connection);
}
}
else
CloseConnection(connection);
}
catch (Exception e)
{
CloseConnection(connection);
Console.WriteLine(e.ToString());
}
}
When I send data from the client side many times one after another very quickly, i don't receive these data separately in the server. I receive them as one large data burst. I need send the reply for every received data . But i can't do it, because these data join in one large burst. How can I send reply for every received data?
Here the code of callback method in the server:
private void RecieveCallback(IAsyncResult asyncResult)
{
ConnectionInfo connection = (ConnectionInfo)asyncResult.AsyncState;
try
{
int bytesRead = connection.Socket.EndReceive(asyncResult);
if (bytesRead > 0)
{
for (int i = 0; i < bytesRead; i++)
connection.FullBufferReceive.Add(connection.BufferReceive[i]);
if (bytesRead == connection.BufferReceive.Length)
{
connection.Socket.BeginReceive(connection.BufferReceive, 0, connection.BufferReceive.Length, 0,
new AsyncCallback(RecieveCallback), connection);
Console.WriteLine("Bytes recieved -- " + bytesRead + " by " + connection.Id);
}
else
{
Console.WriteLine("Bytes recieved " + bytesRead + " by " + connection.Id);
_serverController.StartProcess(connection);
}
}
else
CloseConnection(connection);
}
catch (Exception e)
{
CloseConnection(connection);
Console.WriteLine(e.ToString());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的套接字是 TCP(我无法从代码中看出),这是预期的行为,因为 TCP 不像 UDP 那样被构建。您需要自己界定数据。
If your sockets are TCP (I can't tell from the code), this is expected behavior as TCP isn't framed like UDP is. You need to delimit the data yourself.