/// <summary>写命令</summary> /// <param name="cmd"></param> private void Write(SGIPEntity cmd) { if (Client == null || !Client.Client.Connected) { throw new InvalidOperationException("没有连接到服务器!"); } if (cmd.SrcNodeSequence < 1) { cmd.SrcNodeSequence = SrcNodeSequence; } try { try { Client.Send(cmd.GetStream().ReadBytes()); } catch (Exception ex) { throw new Exception("发送" + cmd.Command + "指令失败!", ex); } WriteLog("发包:" + cmd); } catch (IOException ex) { throw new InvalidOperationException("写" + cmd.Command + "命令失败!", ex); } }
/// <summary>登录。发送Bind指令,接收Bind_Resp响应</summary> /// <returns></returns> public Boolean Login() { WriteLog(String.Format("正在连接服务器…… {0}:{1}", IP, Port)); var client = new TcpSession(); Client = client; try { //client.Connect(IP, Port); //client.Connect(IP, Port); client.Remote.Host = IP; client.Remote.Port = Port; } catch (Exception ex) { var str = IP + ":" + Port.ToString(); throw new NetException("连接网关服务器" + str + "出错,请确定网络是否畅通!" + ex.Message, ex); } var cmd = new SGIPBind(); cmd.LoginName = SystemID; cmd.LoginPassowrd = Password; cmd.LoginType = LoginTypes.SpToSmg; WriteLog("正在登录……"); var session = client as ISocketSession; session.Send(cmd.GetStream().ReadBytes()); var pk = client.Receive(); var resp = SGIPEntity.Read(pk.GetStream()) as SGIPResponse; if (resp == null) { throw new Exception("登录失败!服务器没有响应!"); } if (resp.Result != SGIPErrorCodes.Success) { throw new Exception("登录失败!" + resp.Result.GetDescription()); } //登录完成,开始读取指令 client.Received += Client_Received; client.Open(); Logined = true; WriteLog("登录成功!"); return(true); }
/// <summary>读命令</summary> /// <returns></returns> private SGIPEntity Read() { if (Client == null || !Client.Client.Connected) { throw new InvalidOperationException("没有连接到服务器!"); } try { var cmd = SGIPEntity.Read(Client.Receive().GetStream()); if (cmd == null) { throw new Exception("获取命令失败!"); } WriteLog("收包:" + cmd.ToString()); return(cmd); } catch (IOException ex) { throw new InvalidOperationException("读命令失败!", ex); } }
/// <summary>发送指令,返回响应</summary> /// <param name="command">指令</param> /// <returns>响应</returns> private SGIPEntity Send(SGIPEntity command) { Write(command); return(null); }