private void ConnectCallback(IAsyncResult ar) { ConnectStateObject state = (ConnectStateObject)ar.AsyncState; try { state.workSocket.EndConnect(ar); this.IsConnected = true; StartReceive(); } catch (SocketException ex) { state.errorType = (SocketError)ex.ErrorCode; --state.timesToTry; if (state.timesToTry <= 0) { return; } state.workSocket.BeginConnect(state.endPoint, new System.AsyncCallback(ConnectCallback), state); } finally { SocketConnectEvent?.Invoke(this, new SocketConnectEventArgs(state, this)); if (state.externalCallback != null) { state.externalCallback(this, new SocketConnectEventArgs(state, this)); } } }
// async Connect public void StartConnect(IPEndPoint ep, int timesToTry, SocketConnectEventHandler externalCallback = null, object externalCallbackState = null) { if (this.IsConnected == true) { return; } ConnectStateObject state = new ConnectStateObject(); state.workSocket = _socket; state.endPoint = ep; state.timesToTry = timesToTry; state.externalCallback = externalCallback; state.externalCallbackState = externalCallbackState; _socket.BeginConnect(ep, new System.AsyncCallback(ConnectCallback), state); }
public SocketConnectEventArgs(ConnectStateObject state, SockBase handler) { State = state; Handler = handler; }