/// <summary> /// 接收任务 /// </summary> async void Receive(BaseToken t) { try { byte[] buff = new byte[1024]; int msg = await t.socket.ReceiveAsync(new ArraySegment <byte>(buff), SocketFlags.None); if (msg == 0) { t.CloseDe(t, "客户端断开连接"); return; } byte[] value = new byte[msg]; Buffer.BlockCopy(buff, 0, value, 0, msg); t.Receive <T1>(value); //递归 Receive(t); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); Debugger.Error(ex.ToString()); t.CloseDe(t, "客户端断开连接"); } }
/// <summary> /// 连接关闭 /// </summary> /// <param name="token"></param> /// <param name="error"></param> protected void ClientClose(BaseToken token, string error) { try { lock (token) { center.OnClientClose(token, error); token.Close(); tokens.Push(token); maxConn_se.Release(); } } catch (Exception ex) { Debugger.Error(ex.ToString()); } }
/// <summary> /// 监听任务 /// </summary> async void Accept() //async 与 await 的组合是简写 TAP 模式的语法 //Console.WriteLine("正在监听"); { Debugger.Trace("开启新监听"); //编译器遇到await时,等待异步操作(await语句后面的方法会直到有连接进来才会执行),并把控制流程退回到调用此方法处执行 Socket s = await socket.AcceptAsync(); //取出token 并循坏监听消息 maxConn_se.WaitOne(); BaseToken t = tokens.Pop(); t.socket = s; center.OnClientConnent(t); t.ReceiveAsync <T1>(); //Receive(t); //递归 Accept(); }