public bool Accept(ushort port) { this._port = port; if (_socket != null) { return(false); } if (!TcpMng.IsAvailable) { return(false); } if (Interlocked.CompareExchange(ref _state, (int)State.WAIT, (int)State.IDLE) != (int)State.IDLE) { return(false); } Socket listenSocket = TcpMng.Accept(port); if (listenSocket == null) { return(false); } try { listenSocket.BeginAccept(new AsyncCallback(ListenComplete), listenSocket); return(true); } catch (Exception e) { LOG.Error("tcp Accept exception :{0}", e.ToString()); } return(false); }
private void ListenComplete(IAsyncResult ar) { Socket listenSocket = (Socket)ar.AsyncState; if (_needListenHeartbeat) { try { TcpMng.Listen(_port); } catch (Exception e) { LOG.Error("tcp ListenComplete exception:{0}", e.ToString()); } } try { _socket = listenSocket.EndAccept(ar); if (Interlocked.CompareExchange(ref _state, (int)State.RUN, (int)State.WAIT) != (int)State.WAIT) { _socket.Close(); _socket = null; OnAccept(false); return; } _socket.BeginReceive(recvStream, 0, 2048, SocketFlags.None, new AsyncCallback(RecvComplete), null); IP = _socket.RemoteEndPoint.ToString().Split(':')[0]; OnAccept(true); return; } catch (Exception e) { LOG.Error("tcp ListenComplete _socket exception:{0}", e.ToString()); } _socket = null; OnAccept(false); }