/// <summary> /// 启动服务 /// </summary> /// <param name="localEndPoint"></param> /// <param name="userTokenType"></param> /// <param name="backlog"></param> /// <param name="timeOut"></param> protected void Start(IPEndPoint localEndPoint, Type userTokenType, int backlog = 100000, int timeOut = 2 * 60) { _bufferManager.InitBuffer(); // 预分配的UserToken对象池 MyUserTokenPool = new UserTokenPool(userTokenType, _maxClient, _bufferSize, Operation_Completed); //socket初始化 _listenSock = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _listenSock.SendTimeout = _listenSock.ReceiveTimeout = timeOut; _listenSock.ReceiveBufferSize = _bufferSize; _listenSock.Bind(localEndPoint); _listenSock.Listen(backlog); StartAccept(null); }
public Client(IPEndPoint local, IPEndPoint remote, Encoding encoding, int timeOut = 120) { if (remote == null) { throw new ArgumentNullException("remote"); } _remoteEndPoint = remote; _localEndPoint = local; this.Encoding = encoding; this._timeOut = timeOut; _bufferManager = new BufferManager(_bufferSize * _maxClient * opsToPreAlloc, _bufferSize); _objectPool = new UserTokenPool(); Init(); }
public void Start(int port) { //创建连接池 _pool = new UserTokenPool(_maxClient); //连接信号量 _acceptClients = new Semaphore(_maxClient, _maxClient); for (int i = 0; i < _maxClient; i++) { UserToken token = new UserToken(); //初始化token信息 token.receiveSAEA.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Comleted); token.sendSAEA.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Comleted); token.sendProcess = ProcessSend; token.closeProcess = ClientClose; token.center = _center; _pool.push(token); } // 监听当前服务器网卡所有可用IP地址的port端口 // 外网IP 内网IP192.168.x.x 本机IP一个127.0.0.1 try { // 获取以太网有线连接IP //IPAddress ip = IPHelper.GetEthernetIP(NetworkInterfaceType.Ethernet); //if (ip == null) //{ // // 获取以太网无线连接IP // ip = IPHelper.GetEthernetIP(NetworkInterfaceType.Wireless80211); //} IPAddress ip = GetIpAddress(); _server.Bind(new IPEndPoint(ip, port)); // 置于监听状态 _server.Listen(10); StartAccept(null); Console.WriteLine(string.Format("Start Listen, ip: {0}, port: {1}. \n", ip, port)); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// 异步Socket TCP服务器 /// </summary> /// <param name="localIPAddress">监听的IP地址</param> /// <param name="listenPort">监听的端口</param> /// <param name="maxClient">最大客户端数量</param> public Server(IPAddress localIPAddress, int listenPort, int maxClient, Encoding encoding, int timeOut = 120) { this.Address = localIPAddress; this.Port = listenPort; this.Encoding = encoding; _maxClient = maxClient; _serverSock = new Socket(localIPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _bufferManager = new BufferManager(_bufferSize * _maxClient * opsToPreAlloc, _bufferSize); _objectPool = new UserTokenPool(); _maxAcceptedClients = new SemaphoreSlim(_maxClient, _maxClient); _connectedSockets = new ConcurrentDictionary <IntPtr, Socket>(DefaultConcurrencyLevel, _maxClient); }