【发布时间】:2013-02-15 00:33:29
【问题描述】:
我正在设置一个套接字来监听传入的连接:
public Socket Handler;
public void StartListening()
{
// Establish the locel endpoint for the socket
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
// Create a TCP/IP socket
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
// Bind the socket to the local endpoint and listen
listener.Blocking = false;
listener.Bind(localEndPoint);
listener.Listen(100);
// Start an asynchronous socket to listen for connections
listener.BeginAccept( new AsyncCallback(AcceptCallback), listener);
}
catch (Exception e)
{
invokeStatusUpdate(0, e.Message);
}
}
private void AcceptCallback(IAsyncResult ar)
{
// Get the socket that handles the client request
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
Handler = handler;
// Create the state object
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
正如您在上面看到的,一旦建立连接,我就会设置我的 BeginReceive 回调。这很好用。
最终我想关闭当前连接,然后再次开始在我的套接字上监听传入连接尝试:
public void CloseNode(bool restart)
{
try
{
if (Handler != null)
{
Handler.Shutdown(SocketShutdown.Both);
Handler.Close();
Handler.Dispose();
Handler = null;
}
if (restart)
StartListening();
}
catch (Exception e)
{
invokeStatusUpdate(0, e.Message);
}
}
我的 close 方法需要一个布尔值来判断它是否应该开始监听更多的传入连接。
问题是当我回到我的StartListening 方法时,我在listener.Bind(localEndPoint); 行上得到一个异常,说“每个套接字地址(协议/网络地址/端口)只有一种用法是通常允许”。
如何设置我的收听以重新开始收听?
【问题讨论】: