我有以下兩個函數來啓動和停止「本地服務器」(套接字監聽器)。套接字重用不起作用
public String startServer(Int32 port, Int32 maximumPendingConnections, ref String errorMsg) {
try {
// Creates one SocketPermission object for access restrictions
permission = new SocketPermission(
NetworkAccess.Accept, // Allowed to accept connections
TransportType.Tcp, // Defines transport types
"", // The IP addresses of local host
SocketPermission.AllPorts // Specifies all ports
);
// Listening Socket object
sListener = null;
// Ensures the code to have permission to access a Socket
permission.Demand();
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("");
// Gets first IP address associated with a localhost
ipAddr = ipHost.AddressList[0];
// Creates a network endpoint
ipEndPoint = new IPEndPoint(ipAddr, port);
// Create one Socket object to listen the incoming connection
sListener = new Socket(
ipAddr.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
// Associates a Socket with a local endpoint
sListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //newly added as an answer
sListener.Bind(ipEndPoint);
sListener.Listen(maximumPendingConnections);
// Begins an asynchronous operation to accept an attempt
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener);
} catch (Exception e) {
//ErrorHandling
}
return ipAddr.ToString();
}
停止連接:
public void stopServer(ref String errorMsg) {
try {
sListener.Shutdown(SocketShutdown.Both);
sListener.Disconnect(true);
sListener.Close();
sListener.Dispose();
} catch (Exception e) {
//Errorhandling
}
}
我已經讓你無法重複使用套接字發現,但是如果你設置sListener.Disconnect(true);
它應該能夠重新使用。除此之外,我每次開始創建一個新的套接字。我在這裏錯過了什麼?
它給出了每個套接字只能使用一次的錯誤。它提供了14:41的sListener.Bind(ipEndPoint);
@Edit錯誤 - 16-12-2015 我發現,如果我的sListener.Bind(ipEndPoint);
它的工作原理之前添加以下代碼行;
sListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
謝謝您關於連接財產的額外建議。我會改變這個,序列就是vovanrock所說的。但我想我只是喜歡踢:-p(也會改變這個問題) – Sliver2009