Socket.send() 在服务器中挂起/休眠
我有这个方法,我用它来发送 Transfer 对象。
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 7777);
Socket sockListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sockListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sockListener.Bind(ipEnd);
sockListener.Listen(100);
s = sockListener.Accept();
private void sendToClient(Transfer.Transfer tt)
{
byte[] buffer = new byte[15000];
IFormatter f = new BinaryFormatter();
Stream stream = new MemoryStream(buffer);
f.Serialize(stream, tt);
Console.WriteLine("1/3 serialized");
stream.Flush();
Console.WriteLine("2/3 flushed stream");
s.Send(buffer, buffer.Length, 0);
Console.WriteLine("3/3 send to client");
}
奇怪的是,它在我调用它的前两次起作用,然后在第三次调用时它挂在 s.send() 上。
如果我想发送字符串而不是传输,它是一样的。
I have this method which i use to send a Transfer object
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 7777);
Socket sockListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sockListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sockListener.Bind(ipEnd);
sockListener.Listen(100);
s = sockListener.Accept();
private void sendToClient(Transfer.Transfer tt)
{
byte[] buffer = new byte[15000];
IFormatter f = new BinaryFormatter();
Stream stream = new MemoryStream(buffer);
f.Serialize(stream, tt);
Console.WriteLine("1/3 serialized");
stream.Flush();
Console.WriteLine("2/3 flushed stream");
s.Send(buffer, buffer.Length, 0);
Console.WriteLine("3/3 send to client");
}
The strange thing is it work the first 2 times i call it, then on the 3rd call it hangs on s.send().
Its the same if i want to send String instead of Transfer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@nos 的评论可能是正确的,TCP 发送缓冲区可能已满,并且对 s.send() 的第三次调用处于阻塞状态,直到数据通过网络发送为止。您可以这样设置使用的缓冲区大小:
您应该能够通过将缓冲区大小设置为要发送的数据大小的较大倍数来确认您的问题。
另外,根据建议,您应该检查客户端以确保其正确读取数据。
The comment by @nos is probably correct, the TCP Send buffer is probably filling up and the 3rd call to s.send() is blocking until the data is sent over the network. You can set the used buffer sizes like this:
You should be able to confirm your problem by setting your buffer sizes to a larger multiple of the size of data you're sending.
Also, as suggested, you should check the client to make sure its reading the data properly.