私はC#でWindowsフォームアプリケーションを使っています。私は非同期の方法でサーバーに接続しているソケットクライアントを使用しています。接続が何らかの理由で壊れた場合、ソケットを直ちにサーバーに再接続しようとします。問題に近づくための最良のデザインはどれですか?接続が失われてもサーバーに再接続しようとしているかどうかを継続的に確認しているスレッドを作成する必要がありますか?ここでソケットクライアントを自動的に再接続する設計の選択
は、ソケット通信を処理している私のXcomClientクラスのコードです:
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)
{
if (!this.socketClient.Connected)
StartConnecting();
else
{
}
}
}
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 (SocketException e)
{
NotifyClientStatusSubscribers(false);
}
}
今日は、受信したバイト数を確認するか、ソケット例外をキャッチすることにより、断線をキャッチしてみてください。
どのクラスを使用するかによって異なります。ここであなたのコードを投稿するか、私たちにもっと情報を与えてください。 –