/*---------------------------------------------------------------- // Copyright (C) 2007 liu523@QQ.COM // 版权所有。 // 开发者:liu523@QQ.COM团队 // 文件名:BaseCommunication.cs // 文件功能描述:基本通讯类,本身不能直接当作网络通讯使用,被BaseServer和BaseControler继承。 //----------------------------------------------------------------*/ using System; using System.Text; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using System.Windows.Forms; using RemoteControlLib.Common; using RemoteControlLib.Codes; namespace RemoteControlLib.Bases { /// /// 执行指令的委托 /// /// 指令 public delegate void ExecuteCodeEvent(BaseCommunication sender, Code code); /// /// 基本通讯类 /// public class BaseCommunication { /// /// 序列化网络流读者 /// private BinaryFormatter formatterReader; /// /// 序列化网络流写者 /// private BinaryFormatter formatterWriter; /// /// 网络流 /// protected NetworkStream stream; /// /// 端口 /// protected int port; /// ///获取等待重试时间 /// protected virtual int sleepTime { get { return Constant.SleepTime; }//默认值 } /// ///是否断开连接 /// public bool Disconnected; /// /// 是否退出(不再连接) /// public bool Exit; /// /// 委托(执行指令) /// public ExecuteCodeEvent Execute; /// /// 客户端基类构造函数 /// public BaseCommunication() { Disconnected =true; Exit = false; formatterReader = new BinaryFormatter(); formatterWriter = new BinaryFormatter(); } /// /// 传输信息 /// protected void communication() { try { Disconnected = false; do { //读取网络流 Code code = (Code)formatterReader.Deserialize(stream); if (code != null) { if (code.Head == CodeHead.CONNECT_CLOSE) Disconnected = true; else if (code.Head == CodeHead.EXIT) { Disconnected = true; Exit = true; } else Execute(this, code); } } while (!Disconnected); } catch// (Exception e) { // MessageBox.Show(e.ToString()); } Disconnected = true; } /// /// 告诉对方连接成功 /// protected void SayHello() { try { Disconnected = false; BaseCode ConnectOK = new BaseCode(); ConnectOK.Head = CodeHead.CONNECT_OK; SendCode(ConnectOK); } catch { Disconnected = true; } } /// /// 关闭所有连接 /// /// public void CloseStream() { try { Disconnected = true; if (stream != null) stream.Close(); } catch { } } /// /// 发送指令 /// /// 指令 public void SendCode(Code code) { try { formatterWriter.Serialize(stream, code); } catch// (Exception exp) { // MessageBox.Show("Error:" + exp.ToString()); } } } }