我正在设置一个套接字来侦听传入的连接:
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);
上得到一个异常,说"通常只允许使用每个套接字地址(协议/网络地址/端口)一次"。
我如何设置我的听力开始再次收听?
分为startListening()
和continueListening()
两种方法
Start listening将初始化所有内容,然后调用continue listening。如果您正在拨打电话,请在最后开始收听,请拨打继续收听。
或者,如果您想一次允许多个调用,只需将BeginAccept
调用放入while(true)
循环中。这将永远接受所有传入的连接,即使其他人已经连接。这就是为什么它是异步的!
这是你的成员变量
public Socket Handler;
private socket listener; // added by corsiKa
这是你新的开始方法
public void StartListening()
{
// Establish the locel endpoint for the socket
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
// Create a TCP/IP 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
performListen(listener); // changed by corsiKa
}
catch (Exception e)
{
invokeStatusUpdate(0, e.Message);
}
}
这是你的perform listen方法
// added by corsiKa
private void performListen(Socket listener) {
listener.BeginAccept( new AsyncCallback(AcceptCallback), listener);
}
这是你新的close方法
// variable name changed by corsiKa
public void CloseNode(bool acceptMoreConnections)
{
try
{
if (Handler != null)
{
Handler.Shutdown(SocketShutdown.Both);
Handler.Close();
Handler.Dispose();
Handler = null;
}
// changed by corsiKa
if (acceptMoreConnections)
performListen(listener);
}
catch (Exception e)
{
invokeStatusUpdate(0, e.Message);
}
}