public void Connect(IPEndPoint remoteEndPoint, int timeout) { ManagedConnectState state = new ManagedConnectState(this); this.BeginConnect(remoteEndPoint, buildSocketCallBack, state); if (!connectResetEvent.WaitOne(timeout, false)) { connectResetEvent.Reset(); throw new SocketException((int)SocketError.HostUnreachable); } else { if (state.exception != null) { //done this way because the CallBack is on another thread, so any exceptions it throws will not be caught by calling code throw state.exception; } else { connectResetEvent.Reset(); } } this.BeginReceive(GetReceiveBuffer(settings.ReceiveBufferSize), 0, settings.ReceiveBufferSize, SocketFlags.None, receiveCallBack, null); }
private void BuildSocketCallBack(IAsyncResult ar) { ManagedConnectState state = ar.AsyncState as ManagedConnectState; try { state.socket.EndConnect(ar); } catch (SocketException sex) { state.exception = sex; connectResetEvent.Set(); return; } //Interlocked.Increment(ref socketCount); connectResetEvent.Set(); }