2009-07-08 91 views
4

我身边有类似这样的代码Asynchronous Server Socket Example净停止监听套接字

一切都很正常写了一个窗口服务。客户端/服务器通信完美工作。没有问题。当我尝试关闭Windows服务,我不能没有收到以下错误停止服务器套接字监听:

A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.

我曾尝试以下停止监听的每个组合。但他们都抛出了错误。

listener.Shutdown(SocketShutdown.Both); 
listener.Disconnect(true); 
listener.Close(); 

即使发生错误,套接字也会最终释放并关闭。但是,可能需要一分钟才能重新启动我的Windows服务。我需要能够比这更快地循环Windows服务。请让我知道你是否可以帮忙。谢谢...

回答

1

监听器是您用于.Bind(),.Listen()和.Accept()的套接字,即它不是通过.Connect()连接的套接字,或者是通过接受的连接。接受()?
然后不要调用listener.Discconnect()。

“无用”的细节:
System.Net.Socket.Disconnect使用的(不安全的)函数指针调用(本地)网络扩展功能DisconnectEx

 
Parameters
hSocket [in]
A handle to a connected, connection-oriented socket.
你的监听套接字未连接状态。

2

尝试将LingerState财产

socket.LingerState = new LingerOption(false, 0); 
socket.Shutdown(SocketShutdown.Both); 
socket.Disconnect(false); 
socket.Close(); 

希望这有助于。

+0

根据msdn,LingerOption.Enabled == false是默认值,并且表示默认超时时间为_do_逗留。你认为文档有误吗? http://msdn.microsoft.com/en-us/library/system.net.sockets.lingeroption.lingeroption.aspx – Aaron 2012-02-08 23:56:08