using System; using System.Diagnostics; using System.Net.Sockets; namespace Bro.Common.Link { /// /// TCP连接 /// public class TCPLink : LinkBase { // 网络连接数据流 public NetworkStream netStream = null; // 远端信息 public string remoteInfo {get;set;} // 是否远端关闭 public bool IsRemoteDisconn {get;set;} public TCPLink(NetworkStream stream) { this.netStream = stream; this.IsRemoteDisconn = false; } public TCPLink() { this.IsRemoteDisconn = false; } /// /// 初始化 /// /// public override bool Init() { // TODO: return true; } /// /// 打开TCP连接 /// /// public override bool Open() { // TODO: return true; } /// /// 关闭TCP连接 /// public override void Close() { // TODO: if ( null == this.netStream ) { return; } try { this.netStream.Close(); this.netStream = null; this.IsRemoteDisconn = true; } catch(Exception ex) { Trace.TraceError("TCPLink:{0} Close fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace); } } /// /// 销毁 /// public override void Fnit() { this.Close(); } /// /// 接收数据 /// /// public override int Recv(byte[] rcvBuf, int bufLen) { int len = -1; try { len = netStream.Read(rcvBuf, 0, bufLen); } catch(Exception ex) { this.IsRemoteDisconn = true; Trace.TraceError("TCPLink:{0} Recv fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace); } return len; } /// /// 发送数据 /// /// /// public override bool Send(byte[] sndBuf, int offset, int len) { try { netStream.Write(sndBuf, offset, len); return true; } catch(Exception ex) { this.IsRemoteDisconn = true; Trace.TraceError("TCPLink:{0} Send fail, ex:{1}-{2}", this.Desp, ex.Message, ex.StackTrace); } return false; } } }