如何重用插座.NET? [英] How to reuse socket in .NET?
问题描述
我尝试重新连接到我从断开的插槽,但它不会允许它由于某种原因,即使我叫Disconnect方法与参数reuseSocket设置为true。
_socket =新的Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
_socket.Connect(ip地址,端口);
//...receive数据
_socket.Disconnect(真正的); // reuseSocket =真
//...等待
_socket.Connect(ip地址,端口); //引发InvalidOperationException:
在插座已经断开, 你只能再次重新连接 异步的,只有一个 不同的端点。 BeginConnect绝 被称为一个线程,不会退出 直到操作一直 完成。
我是什么做错了吗?
阅读MSDN文档的 Socket.Disconnect 我注意到一些可能会造成您的问题。
如果您需要致电断开不先调用关机,可以设定 SocketOption 名为 DontLinger 以
假
并指定一个非零的超时间隔,以确保数据排队等待出站发送传输。 断开然后阻塞,直到数据被发送或直到指定超时过期。如果设置DontLinger为false,并且指定了零超时间隔,关闭释放连接,并自动放弃传出排队数据。
尝试将 DontLinger
套接字选项,并指定0超时或使用关闭
调用断开连接。<前/ P>
I am trying to reconnect to a socket that I have disconnected from but it won't allow it for some reason even though I called the Disconnect method with the argument "reuseSocket" set to true.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(ipAddress, port);
//...receive data
_socket.Disconnect(true); //reuseSocket = true
//...wait
_socket.Connect(ipAddress, port); //throws an InvalidOperationException:
Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed.
What am I doing wrong?
After reading the MSDN documentation for Socket.Disconnect I noticed something that might be causing your issue.
If you need to call Disconnect without first calling Shutdown, you can set the SocketOption named DontLinger to
false
and specify a nonzero time-out interval to ensure that data queued for outgoing transmission is sent. Disconnect then blocks until the data is sent or until the specified time-out expires. If you set DontLinger to false and specify a zero time-out interval, Close releases the connection and automatically discards outgoing queued data.
Try setting the DontLinger
Socket option and specify a 0 timeout or use Shutdown
before you call disconnect.
这篇关于如何重用插座.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!