private void ProcessReceive(SocketAsyncEventArgs e) { // check if the remote host closed the connection UserToken token = e.UserToken as UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { // 이후의 작업은 CUserToken에 맡긴다. token.OnReceive(e.Buffer, e.Offset, e.BytesTransferred); // 다음 메시지 수신을 위해서 다시 ReceiveAsync매소드를 호출한다. bool pending = token.Socket.ReceiveAsync(e); if (!pending) { ProcessReceive(e); } } else { token.Close(); Console.WriteLine(string.Format("error {0}, transferred {1}", e.SocketError, e.BytesTransferred)); //close_clientsocket(token); } }
/// <summary> /// 客户端断开连接 /// </summary> /// <param name="token"> 断开连接的用户对象</param> /// <param name="error">断开连接的错误编码</param> public void ClientClose(UserToken token, string error) { if (token.conn != null) { lock (token) { //通知应用层面 客户端断开连接了 center.ClientClose(token, error); token.Close(); //加回一个信号量,供其它用户使用 pool.Push(token); acceptClients.Release(); } } }
/// <summary> /// 关闭连接 /// </summary> /// <param name="error"></param> /// <returns></returns> protected override bool CloseCON(UserToken token, string error) { if (token.HasConnection()) { lock (token) { token.Close(); ServerNetCenter.Instance.OnConnClosed(token, error); return(true); } } else { return(false); } }
///// <summary> ///// AcceptSocket回调 ///// </summary> ///// <param name="ar"></param> //private void AcceptSocketCallback(IAsyncResult ar) //{ // Thread thread = new Thread(() => { // //TcpListener listener = (TcpListener)ar.AsyncState; // //Socket socket = listener.EndAcceptSocket(ar); // //localsocket // Socket localSocket = (Socket)ar.AsyncState; // //接入socket // Socket socket = localSocket.EndAccept(ar); // UserToken token = new UserToken(socket); // string receive = null; // try // { // receive = token.Receive(); // } // //异常 // catch // { // token.Close(); // clientConnected.Set(); // return; // } // token.Session = SessionFactory(receive); // string identity = token.Session.Accredit(receive); // if (string.IsNullOrWhiteSpace(identity)) // { // token.Close(); // token = null; // } // else // { // token.Identity = identity; // _tokenPool.AddUserToken(token); // try // { // token.Listener(); // } // catch // { // token.Close(); // } // } // }); // thread.IsBackground = true; // thread = UserThreadPool.AddThread("[ServerAcceptSocket]", thread); // thread.Start(); // //var autoReset = new AutoResetEvent(false); // //autoResetEventDict.TryGetValue(Thread.CurrentThread.ManagedThreadId, autoReset, (x, y) => autoReset); // clientConnected.Set(); //} /// <summary> /// 接入socket /// </summary> /// <param name="clientSocket"></param> private void AcceptSocket(Socket clientSocket) { //TcpListener listener = (TcpListener)ar.AsyncState; //Socket socket = listener.EndAcceptSocket(ar); //clientSocket.ReceiveTimeout = _tcpServerConfig.AccreditReceiveTimeout; UserToken token = new UserToken(clientSocket, _iLog, _tokenPool); token.Session = _accreditHandle.Accredit(token); if (token.Session == null) { if (_iLog != null) { _iLog.LogError(string.Format("授权失败\r\n{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), null); } //if (_accreditHandle != null) //{ // try // { // token.Send(_accreditHandle.AccreditFailSendMessage()); // } // catch { } //} token.Close(); return; } else { if (_iLog != null) { _iLog.LogDebug(string.Format("授权成功\r\nIdentity:{0}\r\n{1}", token.Session.Identity, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); } } string identity = token.Session.Identity; if (string.IsNullOrWhiteSpace(identity)) { token.Close(); token = null; } else { token.Identity = identity; _tokenPool.AddUserToken(token); if (AcceptSuccess != null) { AcceptSuccess(token); } //token.Socket.ReceiveTimeout = -1; Action clientListener = () => { while (true) { string msg = null; try { msg = token.Receive(); if (string.IsNullOrWhiteSpace(msg)) { continue; } } #if ANDROID catch (System.IO.IOException ex) { } #endif catch (Exception ex) { _tokenPool.RemoveUserToken(token.Identity); token.Close(); } //异常 if (msg == null) { return; } token.Session.ProcessReceive(msg, token); } }; Thread _listenerThread = new Thread(() => { clientListener(); }); //thread = UserThreadPool.AddThread(Identity, thread); _listenerThread.IsBackground = true; _listenerThread.Start(); } //var autoReset = new AutoResetEvent(false); //autoResetEventDict.TryGetValue(Thread.CurrentThread.ManagedThreadId, autoReset, (x, y) => autoReset); //clientConnected.Set(); }