private void Accept_Completed(object sender, SocketAsyncEventArgs e) { StateObject state = null; if (e.SocketError == SocketError.Success) { var io = _ioEventPool.Pop(); state = (io.UserToken as StateObject); try { System.Net.Sockets.Socket sock = e.AcceptSocket; state.Handle = _acceptCount.CountAdd(); state.Socket = sock; var option = new TcpKeepAlive { OnOff = 1, KeepAliveTime = 5000, KeepAliveInterval = 1000 }; state.Socket.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null); AddPeer(io); OnAccepted(state); BeginReceive(io); } catch (System.Exception ex) { Trace.WriteLine("Accept Exception : " + ex.Message); ClosePeer(state); } finally { _allDone.Set(); } } }
public void Connect(string ip, int port, int timeout = 5000) { try { if (IsConnect()) return; this.ip = ip; this.port = port; _remoteEP = new IPEndPoint(IPAddress.Parse(ip), port); if (_stateObject.Socket == null) { System.Net.Sockets.Socket handler = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult asyncResult = handler.BeginConnect(_remoteEP, null, null); if (asyncResult.AsyncWaitHandle.WaitOne(timeout, true)) { handler.EndConnect(asyncResult); _stateObject.Socket = handler; var option = new TcpKeepAlive { OnOff = 1, KeepAliveTime = 5000, KeepAliveInterval = 1000 }; _stateObject.Socket.IOControl(IOControlCode.KeepAliveValues, option.GetBytes(), null); BeginReceive(_ioEvent); OnConnected(_stateObject); } else { _stateObject.Init(); throw new SocketException(10060); } } else { _stateObject.Init(); } } catch (ArgumentNullException arg) { throw new Exception.Exception(arg.Message); } catch (SocketException se) { throw new Exception.Exception(se.Message); } catch (System.Exception e) { throw new Exception.Exception(e.Message); } }