2
나는 C#에서 Windows 양식 응용 프로그램을 사용하고 있습니다. 비동기 방식으로 서버에 연결하는 소켓 클라이언트를 사용하고 있습니다. 어떤 이유로 든 연결이 끊어진 경우 소켓에서 즉시 서버에 다시 연결하려고합니다. 처럼 일상적인 모습을 받게 내이비동기 소켓 클라이언트를 자동으로 다시 연결
(false)를 NotifyClientStatusSubscribers는 함수 StopClient이 실행될 때 호출 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)
{
}
}
:
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();
}
}
:
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)
{
}
}
지금 나는 다음과 같은 함수를 호출하여 다시 연결 시도
연결이 가능할 때 소켓이 다시 연결되지만 몇 초 후에 다음과 같은 처리되지 않은 예외가 발생합니다. "이미 연결된 소켓에서 연결 요청이 이루어졌습니다."
어떻게 가능합니까?