private TcpAcceptor(int port, ILogFile log, AcceptedCallback acceptedCallback) { _log = log; _port = port; _acceptedCallback = acceptedCallback; _thr = ForeverThread.New(accepting_loop, log); _acceptor = new TcpListener(IPAddress.Any, _port); }
private void ProcessAcceptCallback(SocketAsyncEventArgs e) { if (_isStoped || _maxNumberOfConnections <= _numberOfConnections || e.SocketError != SocketError.Success) { DisposeSocketArgs(e); return; } //从对象池中取出一个对象 var tArgs = _acceptTokenManager.GetEmptyWait((retry) => true); if (tArgs == null) { DisposeSocketArgs(e); return; //throw new Exception(string.Format("已经达到最大连接数max:{0};used:{1}", // maxNumberOfConnections, numberOfConnections)); } Interlocked.Increment(ref _numberOfConnections); var sToken = ((SocketToken)tArgs.UserToken); sToken.TokenSocket = e.AcceptSocket; sToken.TokenSocket.ReceiveTimeout = receiveTimeout; sToken.TokenSocket.SendTimeout = sendTimeout; sToken.TokenIpEndPoint = (IPEndPoint)e.AcceptSocket.RemoteEndPoint; sToken.TokenAgrs = tArgs; tArgs.UserToken = sToken; //listening receive if (e.AcceptSocket.Connected) { if (!e.AcceptSocket.ReceiveAsync(tArgs)) { ProcessReceiveCallback(tArgs); } //将信息传递到自定义的方法 AcceptedCallback?.Invoke(sToken); } else { ProcessDisconnectCallback(tArgs); } if (_isStoped) { return; } //继续准备下一个接收 StartAccept(e); }
/// <summary> /// 处理客户端连接 /// </summary> /// <param name="e"></param> private void ProcessAccept(SocketAsyncEventArgs e) { try { if (stoped) { if (e.ConnectSocket != null) { e.ConnectSocket.Close(); e.ConnectSocket.Dispose(); e.Dispose(); } return; } //从对象池中取出一个对象 SocketAsyncEventArgs tArgs = acceptPool.Pop(); if (maxNumber == numberOfConnections || tArgs == null) { throw new Exception("已经达到最大连接数"); } Interlocked.Increment(ref numberOfConnections); ((SocketToken)tArgs.UserToken).TokenSocket = e.AcceptSocket; //继续准备下一个接收 if (!e.AcceptSocket.ReceiveAsync(tArgs)) { ProcessReceive(tArgs); } //将信息传递到自定义的方法 AcceptedCallback?.Invoke(tArgs.UserToken as SocketToken); } catch (Exception ex) { throw ex; } if (stoped) { return; } //继续监听 StartAccept(e); }
public static ITcpAcceptor New(int port, ILogFile log, AcceptedCallback acceptedCallback) { return new TcpAcceptor(port, log.WrapIfNull(), acceptedCallback); }