我正在使用 C# 中的 Windows 窗体应用程序。我正在使用以异步方式连接到服务器的套接字客户端。如果连接因任何原因断开,我希望套接字立即尝试重新连接到服务器。我的接收程序看起来像这样
public void StartReceiving()
{
StateObject state = new StateObject();
state.workSocket = this.socketClient;
socketClient.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(OnDataReceived), state);
}
private void OnDataReceived(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int iReadBytes = client.EndReceive(ar);
if (iReadBytes > 0)
{
byte[] bytesReceived = new byte[iReadBytes];
Buffer.BlockCopy(state.buffer, 0, bytesReceived, 0, iReadBytes);
this.responseList.Enqueue(bytesReceived);
StartReceiving();
receiveDone.Set();
}
else
{
NotifyClientStatusSubscribers(false);
}
}
catch (Exception e)
{
}
}
当 NotifyClientStatusSubscribers(false) 被调用时,函数 StopClient 被执行:
public void StopClient()
{
this.canRun = false;
this.socketClient.Shutdown(SocketShutdown.Both);
socketClient.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), this.socketClient);
}
private void DisconnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the disconnection.
client.EndDisconnect(ar);
this.socketClient.Close();
this.socketClient = null;
}
catch (Exception e)
{
}
}
现在我尝试通过调用以下函数重新连接:
public void StartClient()
{
this.canRun = true;
this.MessageProcessingThread = new Thread(this.MessageProcessingThreadStart);
this.MessageProcessingThread.Start();
this.socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.socketClient.LingerState.Enabled = false;
}
public void StartConnecting()
{
socketClient.BeginConnect(this.remoteEP, new AsyncCallback(ConnectCallback), this.socketClient);
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// Signal that the connection has been made.
connectDone.Set();
StartReceiving();
NotifyClientStatusSubscribers(true);
}
catch(Exception e)
{
StartConnecting();
}
}
当连接可用时,套接字重新连接,但几秒钟后,我得到以下未处理的异常:“在已连接的套接字上发出了连接请求。”
这怎么可能?