C# 自动重新连接异步套接字客户端
我正在使用C#中的windows窗体应用程序。我使用的是一个套接字客户端,它以异步方式连接到服务器。 如果连接因任何原因中断,我希望套接字立即尝试重新连接到服务器。 我的接收程序如下所示C# 自动重新连接异步套接字客户端,c#,sockets,asynchronous,asyncsocket,winsockets,C#,Sockets,Asynchronous,Asyncsocket,Winsockets,我正在使用C#中的windows窗体应用程序。我使用的是一个套接字客户端,它以异步方式连接到服务器。 如果连接因任何原因中断,我希望套接字立即尝试重新连接到服务器。 我的接收程序如下所示 public void StartReceiving() { StateObject state = new StateObject(); state.workSocket = this.socketClient; socketClient
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();
}
}
当连接可用时,套接字将重新连接,但几秒钟后,我收到以下未处理的异常:
“已在已连接的套接字上发出连接请求。”
这是怎么可能的?如果您在
ConnectCallback
中遇到异常,并且您实际上已成功连接,那么这是可能的。在ConnectCallback
的catch语句中设置一个断点,看看是否有异常在那里引发-目前没有任何东西会告诉您有异常