private void StartReceive(AsyncUserToken token) { try { bool willRaiseEvent = token.UserSocket.ReceiveAsync(token.RecvSAEA); if (!willRaiseEvent) { ProcessReceive(token.RecvSAEA); } } catch (Exception e) { Console.WriteLine(e.Message); } }
private void ProcessAccept(SocketAsyncEventArgs e) { AsyncUserToken token = m_userTokenPool.Pop(); token.UserSocket = e.AcceptSocket; //token.m_socket.NoDelay = false; //通知应用层,有客户端连接 handlerCenter.ClientConnect(token); //开启消息到达监听 StartReceive(token); //释放当前异步对象 StartAccept(e); }
private void ClientClose(AsyncUserToken token, string error) { if (token.UserSocket != null) { lock (token) { //通知应用层 客户端断开连接 handlerCenter.ClientClose(token, error); token.Close(); m_userTokenPool.Push(token); m_semaphore.Release(); Console.WriteLine(error); } } }
public void Start(int port) { //创建连接池 m_userTokenPool = new AsyncUserTokenPool(m_nMaxClient); //创建信号量 m_semaphore = new Semaphore(m_nMaxClient, m_nMaxClient); for (int i = 0; i < m_nMaxClient; i++) { AsyncUserToken token = new AsyncUserToken(); token.RecvSAEA.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); token.SendSAEA.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); token.lengthEncode = lengthEncode; token.lengthDecode = lengthDecode; token.messageEncode = messageEncode; token.messageDecode = messageDecode; token.sendProcess = ProcessSend; token.closeProcess = ClientClose; token.handlerCenter = handlerCenter; m_userTokenPool.Push(token); } //监听当前服务器网络所有可用IP地址的port端口 //外网IP,内网IP,本机IP127.0.0.1; try { m_listenSocket.Bind(new IPEndPoint(IPAddress.Any, port)); //置于监听状态 m_listenSocket.Listen(10); StartAccept(null); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// 客户端断开连接 /// </summary> /// <param name="token">断开的客户端对象</param> /// <param name="error">断开的错误信息</param> public abstract void ClientClose(AsyncUserToken token, string error);
/// <summary> /// 收到客户端消息 /// </summary> /// <param name="token">发送消息的客户端对象</param> /// <param name="message">消息内容</param> public abstract void MessageReceive(AsyncUserToken token, int cmd, IMessage message);
/// <summary> /// 客户端连接 /// </summary> /// <param name="token">连接的客户端对象</param> public abstract void ClientConnect(AsyncUserToken token);