protected override void SuccessCallback(MessageStructure writer, MessageHead head) { int type = writer.ReadInt(); if (type == 1) { int recordCount = writer.ReadInt(); JsonObject jsonContainer = new JsonObject(); List <JsonObject> jsonList = new List <JsonObject>(); for (int i = 0; i < recordCount; i++) { writer.RecordStart(); var item = new JsonObject(); item.Add("NoticeID", writer.ReadString()); item.Add("Title", writer.ReadString()); item.Add("Content", writer.ReadString()); item.Add("IsBroadcast", writer.ReadInt()); item.Add("IsTop", writer.ReadInt()); item.Add("Creater", writer.ReadString()); item.Add("CreateDate", writer.ReadString()); item.Add("ExpiryDate", writer.ReadString()); jsonList.Add(item); writer.RecordEnd(); } jsonContainer.Add("total", recordCount); jsonContainer.Add("rows", jsonList.ToArray()); WriteTableJson(jsonContainer); } }
private void OnMessage(byte[] data) { MessageHead cmd = (MessageHead)data[0]; switch (cmd) { case MessageHead.Msg_Set_Session: this.CreateSession(data); break; case MessageHead.Msg_Connect_Work: this._clientAgent.ConnectToServer(this._options.ServiceIPEndPoint); break; case MessageHead.Msg_LogOut: this.LogOut(); break; case MessageHead.Msg_MessageData: this.ProcessPackage(data); break; case MessageHead.Msg_Close_Session: this.ProcessSessionClose(data); break; case MessageHead.Msg_AccessKeyWrong: this.ProcessAccessKeyWrong(); break; } }
/// <summary> /// 向服务器发送消息 /// </summary> /// <param name="head">消息头</param> /// <param name="message">消息内容</param> public OperationReturn SendMessage(MessageHead head, string message) { OperationReturn optReturn = new OperationReturn(); optReturn.Result = true; optReturn.Code = 0; try { if (mTcpClient.Connected) { byte[] bufferData = Encoding.UTF8.GetBytes(message); int size = bufferData.Length; head.Size = size; byte[] bufferHead = Converter.Struct2Bytes(head); mStream.Write(bufferHead, 0, bufferHead.Length); mStream.Write(bufferData, 0, bufferData.Length); mStream.Flush(); } else { optReturn.Result = false; optReturn.Code = Defines.RET_NOT_CONNECTED; optReturn.Message = string.Format("TcpClient not connected"); } } catch (Exception ex) { OnDebug(LogMode.Error, string.Format("SendMessage fail.\t{0}", ex.Message)); optReturn.Result = false; optReturn.Code = Defines.RET_FAIL; optReturn.Message = ex.Message; } return(optReturn); }
public override void OnReceiveTimeout(string clientAddress, byte[] receiveData) { try { BufferReader reader = new BufferReader(receiveData); string paramString = reader.ReadPacketString(); paramString = HttpUtility.UrlDecode(paramString, Encoding.UTF8); int index = paramString.IndexOf("?d="); if (index != -1) { index += 3; paramString = paramString.Substring(index, paramString.Length - index); } PacketMessage receivePacket = ParsePacketMessage(clientAddress, paramString, ConnectType.Tcp); var recHead = receivePacket.Head; int errorCode = LanguageHelper.GetLang().ErrorCode; string errorMsg = LanguageHelper.GetLang().RequestTimeout; MessageHead head = new MessageHead(recHead.MsgId, recHead.ActionId, "st", errorCode, errorMsg); head.HasGzip = true; MessageStructure ds = new MessageStructure(); ds.WriteBuffer(head); byte[] data = ds.ReadBuffer(); OnSendCompleted(clientAddress, data); } catch (Exception ex) { TraceLog.WriteError("Send to client {0} timeout error:{1}", clientAddress, ex); } }
/// <summary> /// 接收消息包 /// </summary> /// <param name="stream"></param> private MessageBag ReceiveMessageBag(NetworkStream stream) { MessageBag bag = null; try { byte[] buffer = Utility.Stream.ReadStream(stream, MessageHead.HeadLength); MessageHead head = MessageHead.Parse(buffer); if (head.BodyLength > 0) { byte[] bytesBody = Utility.Stream.ReadStream(stream, head.BodyLength); bag = new MessageBag(head, bytesBody); } else { bag = new MessageBag(head); } } catch (Exception ex) { ExceptionRecord.Record(ex.Message + ex.Source + ex.TargetSite + ex.StackTrace); throw; } return(bag); }
public void SendToChatServer(MessageHead msg) { if (mTcpConnect != null) { mTcpConnect.SendMesssage(msg); } }
/// <summary> /// 将服务器端发送一条用户退出的指令,前同时删除掉 /// </summary> private static void SendMessage() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string serverIp = config.AppSettings.Settings["ServerIp"].Value; string serverPort = config.AppSettings.Settings["ServerPort"].Value; IPAddress _ipAddress = IPAddress.Parse(serverIp); int _port = Convert.ToInt32(serverPort); try { TcpClient _tcpClient = new TcpClient(); _tcpClient.Connect(_ipAddress, _port); NetworkStream ns = _tcpClient.GetStream(); MessageHead head = new MessageHead((int)MessageType.User, 0, 2); MessageBag bag = new MessageBag(head); bag.BytesBody = Encoding.UTF8.GetBytes(UserID); byte[] buffer = bag.ToBytes(); ns.Write(buffer, 0, buffer.Length); ns.Close(); _tcpClient.Close(); } catch { } }
public MsgRequestGetNodeInfo(long id_, int nodeId_) { Head = new MessageHead(); Head.ID = id_; Head.Type = MessageType.REQUEST_GetNodeInfo; Head.NodeID = nodeId_; }
/// <summary> /// 接收客户端的消息包 /// </summary> /// <param name="stream"></param> private MessageBag ReceiveClientMessage(NetworkStream stream) { LogService.WriteServerRunLog(LogLevel.Info, "接收来自" + _publisherIP + "的不同类型的消息包"); byte[] buffer = Utility.Stream.ReadStream(stream, MessageHead.HeadLength); MessageHead head = MessageHead.Parse(buffer); if (head.BodyLength > 0) { byte[] bytesBody = Utility.Stream.ReadStream(stream, head.BodyLength); MessageType type = (MessageType)head.Type; switch (type) { case MessageType.User: if (head.State == 1) { return(new FirstMessageBag(bytesBody)); } else { //2用户退出时 | //3由CGI发送的UserID return(new MessageBag(head, bytesBody)); } case MessageType.File: //文件是独体,没有其它状态 return(new FileMessageBag(bytesBody)); default: return(new MessageBag(head, bytesBody)); } } return(new MessageBag(head)); }
public MsgRequestShutdownPlayer(long id_, int nodeId_) { Head = new MessageHead(); Head.ID = id_; Head.Type = MessageType.REQUEST_ShutdownPlayer; Head.NodeID = nodeId_; }
public MsgRequestLaunchPlayerFromService(long id_, int nodeId_) { Head = new MessageHead(); Head.ID = id_; Head.Type = MessageType.REQUEST_LaunchPlayerFromService; Head.NodeID = nodeId_; }
public MsgRequestPingService(long id_, int nodeId_) { Head = new MessageHead(); Head.ID = id_; Head.Type = MessageType.REQUEST_PingService; Head.NodeID = nodeId_; }
private void btnResult_Click(object sender, EventArgs e) { #region 客户端发送结果 ShowResult("发送结果"); //发送ready int msgType = MessageType.ClientSendResult; MsgRequestContract contract = new MsgRequestContract("", ""); contract.Key = Guid.NewGuid().ToString(); byte[] bBody = SerializeHelper.SerializeObject(contract); //消息头 MessageHead head = new MessageHead(bBody.Length, msgType); byte[] bHead = head.ToStream(); //构建请求消息 byte[] reqMessage = new byte[bHead.Length + bBody.Length]; Buffer.BlockCopy(bHead, 0, reqMessage, 0, bHead.Length); Buffer.BlockCopy(bBody, 0, reqMessage, bHead.Length, bBody.Length); //发送请求消息 this.tcpPassiveEngine.PostMessageToServer(reqMessage); #endregion }
public void PostMsg(MessageHead msg) { MemoryStream msgStream = new MemoryStream(); byte[] msgid_bytes = BitConverter.GetBytes(msg.msgid); msgStream.Write(msgid_bytes, 0, msgid_bytes.Length); msg.BuidStream(msgStream); MemoryStream stream = new MemoryStream(); //TcpMsgHead 消息头 short index = myself_msg_index_++; short flags = 0; uint datasize = (uint)msgStream.Length; byte[] indexbytes = BitConverter.GetBytes(index); byte[] flagsbytes = BitConverter.GetBytes(flags); byte[] datasizebytes = BitConverter.GetBytes(datasize); stream.Write(indexbytes, 0, indexbytes.Length); stream.Write(flagsbytes, 0, flagsbytes.Length); stream.Write(datasizebytes, 0, datasizebytes.Length); stream.Write(msgStream.ToArray(), 0, (int)msgStream.Length); mSendList.Enqueue(stream); if (myself_msg_index_ >= 32767) { myself_msg_index_ = 0; } }
private void btnReadOne_Click(object sender, EventArgs e) { //发送readdy请求 string code = tbCode.Text.Trim(); if (string.IsNullOrWhiteSpace(code)) { MessageBox.Show("请输入编码"); return; } ShowResult("发送Ready请求"); //客户端发送ready命令 int msgType = NewMessageType.ClientSendReady; MsgRequestContract contract = new MsgRequestContract("", ""); contract.Key = Guid.NewGuid().ToString(); contract.DeviceCode = code;//设备编码 byte[] bBody = SerializeHelper.SerializeObject(contract); //消息头 MessageHead head = new MessageHead(bBody.Length, msgType); byte[] bHead = head.ToStream(); //构建请求消息 byte[] reqMessage = new byte[bHead.Length + bBody.Length]; Buffer.BlockCopy(bHead, 0, reqMessage, 0, bHead.Length); Buffer.BlockCopy(bBody, 0, reqMessage, bHead.Length, bBody.Length); //发送请求消息 this.tcpPassiveEngine.PostMessageToServer(reqMessage); }
private void DoRunProcess(byte[] sendData) { bool readerSuccess = false; bool success = false; try { MessageStructure reader = null; MessageHead head = null; _stepTimer.StartTime(); //Console.WriteLine("DoRunProcess:"+ indentify); _session.Proxy.SendAsync(sendData, data => { // try // { // if (data.Length == 0) return true; // reader = new MessageStructure(data); // head = reader.ReadHeadGzip(); // return head.Action.ToString() == Action; // } // catch (Exception ex) // { // TraceLog.WriteError("Step {0} error:{1}", Action, ex); // return false; // } if (netReader.pushNetStream(data)) { readerSuccess = true; return(true); } else { return(false); } }); if (CheckCompleted(head) && readerSuccess && DecodePacket(reader, head)) { success = true; _stepTimer.Completed(); } else { Console.WriteLine(indentify + " acction error"); } } catch (Exception ex) { _stepTimer.PushError(ex.Message); } finally { _stepTimer.StopTime(); } if (success && ChildStep != null) { ChildStep.StartRun(); } }
protected void btnTest_Click(object sender, EventArgs e) { int contractID = int.Parse(ddlContract.Text); MessageHead msg = new MessageHead(); var paramList = DbDataLoader.GetParamInfo(SlnID, contractID); string requestParams = GetRequestParams(paramList, contractID, txtVersion.Text); string serverUrl = txtServerUrl.Text; string[] keyNames = txtKeyName.Text.Split(new char[] { ',' }); var msgReader = NetHelper.Create(serverUrl, requestParams, out msg, false, contractID, Session.SessionID); if (msgReader != null) { try { if (msg.ErrorCode != 0) { txtResponse.Text = msg.ErrorInfo; } else { txtResponse.Text = BuildLuaFile(paramList, msgReader, keyNames); } } catch (Exception ex) { txtResponse.Text = ex.ToString(); } } }
/// <summary> /// 验证用户 /// </summary> private bool CheckUser() { ClientServer _client = new ClientServer(); _client.StartConn(); MessageHead head = new MessageHead((int)KeywordMessageType.User, 0, 1); byte[] bodyBytes = Service.GetBodyBytes(password, Service.DictVersion, Service.ComputerMac); MessageBag bag = new MessageBag(head, bodyBytes); _client.SendMessage(bag); MessageBag recBag = _client.ReceiveMessage(); if (recBag == null) { Debug.Fail("有错"); } string returnVal = _client.AnalyzeResponeMessage(recBag); _client.CloseConn(); if (string.Compare(returnVal, "true") != 0) { errorInfo = returnVal; return(false); } return(true); }
public static byte[] FeiQWritePackage(MessageHead type, string FromId, string ToId, string msgstr, byte[] fs = null) { byte[] buffer; List <byte> data = new List <byte>(); if (type == MessageHead.File) { MsgHeader obj = new MsgHeader { fromId = FromId, toId = ToId, Msg = msgstr, File = fs, type = (int)type }; string package = jss.Serialize(obj); byte[] msg = Encoding.UTF8.GetBytes(package); data.AddRange(msg); } else { MsgHeader obj = new MsgHeader { fromId = FromId, toId = ToId, Msg = msgstr, type = (int)type }; string package = jss.Serialize(obj); byte[] msg = Encoding.UTF8.GetBytes(package); data.AddRange(msg); } buffer = data.ToArray(); return(buffer); }
protected override bool DecodePacket(MessageStructure reader, MessageHead head) { responsePack = ProtoBufUtils.Deserialize <Response1010Pack>(netReader.Buffer); string responseDataInfo = ""; responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson <Request1010Pack>(req) + "\n"; responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson <Response1010Pack>(responsePack) + "\n"; DecodePacketInfo = responseDataInfo; int childStepId = getChild(1010); System.Console.WriteLine("childStepID:" + childStepId); if (childStepId > 0) { System.Collections.Generic.Dictionary <string, string> dic = new System.Collections.Generic.Dictionary <string, string>(); /* * req.UserID = GetParamsData("UserID", req.UserID); * req.identify = GetParamsData("identify", req.identify); * req.version = GetParamsData("version", req.version); * req.the3rdUserID = GetParamsData("the3rdUserID", req.the3rdUserID); * req.happyPoint = GetParamsData("happyPoint", req.happyPoint); * req.Rate = GetParamsData("Rate", req.Rate); * req.index = GetParamsData("index", req.index); * req.strThe3rdUserID = GetParamsData("strThe3rdUserID", req.strThe3rdUserID); * req.typeUser = GetParamsData("typeUser", req.typeUser); */ dic.Add("UserID", req.UserID.ToString()); dic.Add("index", responsePack.index.ToString()); dic.Add("the3rdUserID", req.the3rdUserID.ToString()); dic.Add("strThe3rdUserID", req.strThe3rdUserID); SetChildStep(childStepId.ToString(), _setting, dic); } return(true); }
public MessageHead PopMessage() { if (mSession == null || !mSession.IsConnected()) { return(null); } MemoryStream stream = mSession.PeekMsg(); if (stream == null) { return(null); } byte[] bytes = new byte[4]; stream.Read(bytes, 0, 4); uint msgid = BitConverter.ToUInt32(bytes, 0); MessageHead head = null; if (msgid == (uint)TCP_MSG_ID.TCP_MSG_SC_CHAT) { head = new SCChatMessage(); head.FromStream(stream); } return(head); }
public void SetFor(MessageHead head) { if (!TrySetFor(head)) { throw new ArgumentException("Could not figure out body encoding"); } }
// ----------解析消息头---------- public static MessageHead UnparseHead(byte[] buffer) { if (buffer.Length >= 13) // 消息头长度足够 { MessageHead head = new MessageHead(); head.HEAD_0 = buffer[0]; head.HEAD_1 = buffer[1]; head.HEAD_2 = buffer[2]; head.HEAD_3 = buffer[3]; head.ProtoVersion = buffer[4]; // (5 6 7 8 9 10 11 12) 错误方法 // System.Array.Reverse(buffer, 5, 8); // (5 6 7 8) (9 10 11 12) 网络序 -> C# 小端序 System.Array.Reverse(buffer, 5, 4); System.Array.Reverse(buffer, 9, 4); // 获取 ServerVersion head.ServerVersion = System.BitConverter.ToInt32(buffer, 5); // 获取 Length head.Length = System.BitConverter.ToInt32(buffer, 9); return(head); } return(null); }
protected virtual bool CheckCompleted(MessageHead head) { // if (head == null || !Equals(head.Action.ToString(), Action)) // { // _stepTimer.PushError(string.Format("Step {0} pid:{1} request timeout.", Action, // _session.Context.PassportId)); // return false; // } // // if (head.ErrorCode >= 10000) // { // _stepTimer.PushError(string.Format("Step {0} pid:{1} request error:{2}-{3}", // Action, // _session.Context.PassportId, // head.ErrorCode, // head.ErrorInfo)); // return false; // } if (netReader == null || int.Parse(Action) != netReader.ActionId) { _stepTimer.PushError(string.Format("Step int.Parse(Action) != netReader.ActionId {0} request timeout.", Action )); return(false); } if (netReader.StatusCode >= 1000) { _stepTimer.PushError(string.Format("Step netReader.StatusCode {0}", Action)); return(false); } return(true); }
protected override bool DecodePacket(MessageStructure reader, MessageHead head) { responsePack = ProtoBufUtils.Deserialize <ResponsePack>(netReader.Buffer); string responseDataInfo = ""; responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson <Request2000Pack>(req) + "\n"; responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson <ResponsePack>(responsePack) + "\n"; DecodePacketInfo = responseDataInfo; int childStepId = getChild(2000); System.Console.WriteLine("childStepID:" + childStepId); if (childStepId > 0) { System.Collections.Generic.Dictionary <string, string> dic = new System.Collections.Generic.Dictionary <string, string>(); /* * req.token = GetParamsData("token",req.token); * req.typeUser = GetParamsData("typeUser",req.typeUser); * req.version = GetParamsData("version", req.version); * req.UserID = GetParamsData("UserID", req.UserID); */ SetChildStep(childStepId.ToString(), _setting, dic); } return(true); }
/// <summary> /// /// </summary> protected virtual void WriteError() { int msgId = paramGetter.GetMsgId(); int actionId = paramGetter.GetActionId(); var head = new MessageHead(msgId, actionId, (int)MessageError.SystemError, ErrorInfo); response.WriteBuffer(head); }
public bool getResult() { if (Reader.Offset == 0) { _head = instance.Reader.ReadHeadGzip(); } return(!_head.Faild); }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <param name="actionGetter"></param> /// <param name="errorCode"></param> /// <param name="errorInfo"></param> public virtual void ResponseError(BaseGameResponse response, ActionGetter actionGetter, int errorCode, string errorInfo) { MessageHead head = new MessageHead(actionGetter.GetMsgId(), actionGetter.GetActionId(), errorCode, errorInfo); MessageStructure sb = new MessageStructure(); sb.WriteBuffer(head); response.BinaryWrite(sb.PopBuffer()); }
/// <summary> /// 出错处理 /// </summary> /// <param name="response"></param> /// <param name="actionID"></param> /// <param name="errorCode"></param> /// <param name="errorInfo"></param> public static void RequestError(IGameResponse response, int actionID, int errorCode, string errorInfo) { MessageHead head = new MessageHead(actionID, errorCode, errorInfo); MessageStructure sb = new MessageStructure(); sb.WriteBuffer(head); response.BinaryWrite(sb.PopBuffer()); }
private void WriteRemote() { int msgId = paramGetter.GetMsgId(); int actionId = paramGetter.GetActionId(); var head = new MessageHead(msgId, actionId, ErrorCode, ErrorInfo); response.WriteBuffer(head); }
public override BaseMessage DynamicCreate (byte[] data, MessageHead head) { if(MessageInfo.MessageTypeCheck(MessageDataType.ProtoBuf)) { ProtobufMessage message = new ProtobufMessage(); message.DataHead = head; message.DataBody.m_SecondValue = data; return message; } return null; }
public override BaseMessage DynamicCreate (byte[] data, MessageHead head) { if(MessageInfo.MessageTypeCheck(MessageDataType.Struct)) { if(head.CMD == 102) { var rdata = (HeartBeatStructData)KTool.BytesToStruct(data,typeof(HeartBeatStructData)); StructMessage value = StructMessage.Create(head,rdata); return value; } } return null; }
public override BaseMessage DynamicCreate (byte[] data, MessageHead head) { if(MessageInfo.MessageTypeCheck(MessageDataType.Json)) { JsonMessage message = new JsonMessage(); message.MessageType = KMessageType.None; if (BitConverter.IsLittleEndian) Array.Reverse(data); message.DataBody.m_FirstValue = System.Text.Encoding.UTF8.GetString(data); if (head != null) { message.DataHead = head; message.MessageType = (KMessageType)head.CMD; } return message; } return null; }
public abstract BaseMessage DynamicCreate(byte[] data, MessageHead head);
private MessageHead Head; //消息头 #endregion Fields #region Constructors public Message() { Head = new MessageHead(); }