/// <summary> /// 发送数据 /// </summary> /// <param name="bts">发送内容</param> /// <param name="comm">命令结构</param> protected void Send(byte[] bts, Record comm) { Thread.Sleep(1); if (Client == null) { return; } if (Client.IsOnlineRead()) { try { lock (Stream) { Stream.BeginWrite(bts, 0, bts.Length, WriteComplete, new NetModel(Stream, comm)); } } catch (Exception ex) { Loghelper.Error(ex); } Loghelper.Debug(string.Format("发送命令:{0} 数据长度:{1}", comm.Type, bts.Length)); } else { OnClientDisconnect(this); } }
private void WriteComplete(IAsyncResult ar) { var netmodel = (NetModel)ar.AsyncState; try { netmodel.NetStream.EndWrite(ar); } catch (Exception ex) { Loghelper.Error(ex); } OnMsgSend(this, netmodel.Record); }
/// <summary> /// 读取发送内容 /// </summary> /// <param name="ar">异步操作</param> protected virtual void ReadComplete(IAsyncResult ar) { try { var stream = (NetworkStream)ar.AsyncState; if (Client.IsOnlineRead()) { var bytesRead = stream.EndRead(ar); Loghelper.Debug(string.Format("读取到 {0} 字节 ...", bytesRead)); if (bytesRead == 0) { return; } string msg = Coding.GetString(Buffer, 0, bytesRead); Array.Clear(Buffer, 0, Buffer.Length); // 清空缓存,避免脏读 var comms = Handler.GetCommand(msg); foreach (Record comm in comms) { ParameterizedThreadStart start = HandleProtocol; start.BeginInvoke(comm, null, null); } // 再次调用BeginRead(),完成时调用自身,形成无限循环 stream.BeginRead(Buffer, 0, BufferSize, ReadComplete, stream); } else { OnClientDisconnect(this); } } catch (Exception e) { Loghelper.Error(e); } }