Exemplo n.º 1
0
 // Server Message
 public static void ServerMessage(string message)
 {
     try
     {
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.ServerMessage,
             Message = message
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         foreach (Client client in sr_clientList)
         {
             client.Socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, client.Socket);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> ServerMessage", @"Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
    /// <summary>
    /// Initiates SendIMMN call to Request Factory
    /// </summary>
    /// <param name="msgToSend">Message object</param>
    private void SendMessage(MessageStructure msgToSend)
    {
        if (null != Session["CSMOBO_ACCESS_TOKEN"])
        {
            this.requestFactory.AuthorizeCredential = (OAuthToken)Session["CSMOBO_ACCESS_TOKEN"];
        }

        if (this.requestFactory.AuthorizeCredential == null)
        {
            Response.Redirect(this.requestFactory.GetOAuthRedirect().ToString());
        }

        try
        {
            SendMessageResponse response = this.requestFactory.SendIMMN(msgToSend.Addresses, msgToSend.Attachments, msgToSend.Message, msgToSend.Subject, msgToSend.Group);
            if (null != response)
            {
                this.DrawPanelForSuccess(statusPanel, response.Id);
            }
        }
        catch (InvalidResponseException ie)
        {
            this.DrawPanelForFailure(statusPanel, ie.Body);
        }
        catch (TokenExpiredException te)
        {
            this.DrawPanelForFailure(statusPanel, te.Message);
        }
        catch (ArgumentException ae)
        {
            this.DrawPanelForFailure(statusPanel, ae.Message);
        }
        catch (UnauthorizedRequest ur)
        {
            this.DrawPanelForFailure(statusPanel, ur.Message);
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(statusPanel, ex.Message);
        }
        finally
        {
            foreach (string file in msgToSend.Attachments)
            {
                if (System.IO.File.Exists(file))
                {
                    try
                    {
                        System.IO.File.Delete(file);
                    }
                    catch { }
                }
            }

            Session["CS_MessageToSend"] = null;
        }
    }
Exemplo n.º 3
0
 public RLUpdateServerStateHandler(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
 }
Exemplo n.º 4
0
 public LWRegisterLobbyServerHandler(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
 }
Exemplo n.º 5
0
        private static void ParseRecordEnd(StringBuilder itemBuilder, MessageStructure reader, List <DataRow> queue, int depth, int recordNum, string[] keyNames)
        {
            MessageStructure msgReader   = reader;
            string           keyValue    = string.Empty;
            string           keyName     = keyNames.Length > depth ? keyNames[depth] : string.Empty;
            List <LuaConfig> builderList = new List <LuaConfig>();
            int recordCount = 0;

            try
            {
                recordCount = msgReader.ReadInt();
            }
            catch { }
            for (int i = 0; i < recordCount; i++)
            {
                try
                {
                    msgReader.RecordStart();
                    int            loopDepth     = 0; //ѭ�����
                    StringBuilder  recordBuilder = new StringBuilder();
                    List <DataRow> recordQueue   = new List <DataRow>();

                    int columnNum = 0;
                    int childNum  = 0;

                    #region ������ȡ����
                    for (int r = 1; r < queue.Count - 1; r++)
                    {
                        DataRow   record     = queue[r];
                        string    fieldName  = record["Field"].ToString();
                        FieldType fieldType  = (FieldType)Enum.Parse(typeof(FieldType), record["FieldType"].ToString());
                        string    fieldValue = "";
                        try
                        {
                            if (loopDepth > 0 && fieldType == FieldType.End)
                            {
                                loopDepth--;
                                recordQueue.Add(record);
                            }
                            if (loopDepth == 0 && recordQueue.Count > 0)
                            {
                                //����ѭ����¼
                                childNum++;
                                var childBuilder = new StringBuilder();
                                ParseRecordEnd(childBuilder, msgReader, recordQueue, depth + 1, childNum, keyNames);
                                //
                                recordQueue.Clear();
                                //ѡ�������ʽ
                                FormatChildToLua(recordBuilder, childBuilder, columnNum);
                            }

                            if (loopDepth == 0)
                            {
                                if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                                {
                                    if (columnNum > 0)
                                    {
                                        recordBuilder.Append(",");
                                    }
                                    if (fieldName.Trim().ToLower() == keyName.Trim().ToLower())
                                    {
                                        keyValue = fieldValue;
                                    }
                                    if (fieldType == FieldType.Byte || fieldType == FieldType.Short || fieldType == FieldType.Int)
                                    {
                                        recordBuilder.AppendFormat("{0}={1}", fieldName, fieldValue);
                                    }
                                    else
                                    {
                                        recordBuilder.AppendFormat("{0}=\"{1}\"", fieldName, fieldValue);
                                    }
                                    columnNum++;
                                }
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                    recordQueue.Add(record);
                                }
                            }
                            else if (fieldType != FieldType.End)
                            {
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                }
                                recordQueue.Add(record);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format("recordindex:{0},fieldName:{1} error:", i, fieldName), ex);
                        }
                    }

                    #endregion
                    //��ȡ�н���
                    msgReader.RecordEnd();
                    builderList.Add(new LuaConfig {
                        Key = keyValue, Builder = recordBuilder
                    });
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("recordindex:{0}error:", i), ex);
                }
            }

            FormatListToLua(itemBuilder, builderList, keyName, depth, recordNum);
        }
Exemplo n.º 6
0
 public static void SendImage(byte[] imgByte)
 {
     try
     {
         MessageStructure msgToSend = new MessageStructure
         {
             UserName = Client.UserName,
             ClientName = Client.Name,
             Command = Command.ImageMessage,
             ImgByte = imgByte
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         s_socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> SendImage", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 7
0
 public RLGetGameConfigsHandler(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
 }
Exemplo n.º 8
0
    /// <summary>
    /// This menthod is called when the page is loading
    /// </summary>
    /// <param name="sender">object pointing to the caller</param>
    /// <param name="e">Event arguments</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            DateTime currentServerTime = DateTime.UtcNow;
            lblServerTime.Text = String.Format("{0:ddd, MMM dd, yyyy HH:mm:ss}", currentServerTime) + " UTC";

            if (this.requestFactory == null)
            {
                bool ableToReadFromConfig = this.ReadConfigFile();
                if (ableToReadFromConfig == false)
                {
                    return;
                }

                this.InitializeRequestFactory();
            }

            if (!Page.IsPostBack)
            {
                if (Session["CSMOBO_ACCESS_TOKEN"] == null)
                {
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        this.authCode = Request["code"];
                        this.requestFactory.GetAuthorizeCredentials(this.authCode);
                        Session["CSMOBO_ACCESS_TOKEN"] = this.requestFactory.AuthorizeCredential;
                    }
                }

                if (null != Session["CS_MessageToSend"])
                {
                    MessageStructure msg = (MessageStructure)Session["CS_MessageToSend"];
                    txtMessage.Text = msg.Message;
                    string temp = string.Empty;

                    foreach (string addr in msg.Addresses)
                    {
                        temp += addr + ",";
                    }

                    if (!string.IsNullOrEmpty(temp))
                    {
                        temp = temp.Substring(0, temp.LastIndexOf(","));
                    }

                    txtPhone.Text    = temp;
                    txtSubject.Text  = msg.Subject;
                    chkGroup.Checked = msg.Group;
                    this.SendMessage(msg);
                }
            }
        }
        catch (InvalidResponseException ie)
        {
            this.DrawPanelForFailure(statusPanel, ie.Body);
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(statusPanel, ex.Message);
        }
    }
Exemplo n.º 9
0
 public static void ChangeColor(Color color)
 {
     try
     {
         //string colorHex = GenericStatic.HexConverter(ColorPicker.Color);
         //ClientConnection.Color = colorHex;
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.ColorChanged,
             UserName = Client.UserName,
             ClientName = Client.Name,
             Color = HexConverter.Convert(color)
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         s_socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> ChangeColor", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 10
0
 private static void OnRegister(IAsyncResult ar)
 {
     try
     {
         Status = true;
         s_socket.EndConnect(ar);
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.Register,
             UserName = Client.UserName,
             ClientName = Client.Name
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         s_socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, null);
         s_byteMessage = new byte[2097152];
         s_socket.BeginReceive(s_byteMessage, 0, s_byteMessage.Length, SocketFlags.None, OnReceive, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> OnRegister", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 11
0
        private static void OnReceive(IAsyncResult ar)
        {
            if (!Status)
            {
                return;
            }
            try
            {
                // Let the server know the message was recieved
                s_socket.EndReceive(ar);
                // Convert message from bytes to messageStracure class and store it in msgReceieved
                MessageStructure msgReceived = new MessageStructure(s_byteMessage);
                // Set new bytes and start recieving again
                s_byteMessage = new byte[2097152];
                if (msgReceived.Command == Command.Disconnect)
                {
                    Status = false;
                    MessageStructure msgToSend = new MessageStructure
                    {
                        Command = Command.Disconnect,
                        ClientName = Client.Name,
                        UserName = Client.UserName
                    };
                    byte[] b = msgToSend.ToByte();
                    s_socket.Send(b, 0, b.Length, SocketFlags.None);
                    s_socket.Shutdown(SocketShutdown.Both);
                    s_socket.BeginDisconnect(true, (OnDisonnect), s_socket);
                    if (ClientNetworkEngineDisconnectEvent != null)
                    {
                        ClientNetworkEngineDisconnectEvent.Invoke();
                    }
                    return;
                }
                if (msgReceived.Command != Command.AttemptLogin && msgReceived.Command != Command.Register)
                {
                    s_socket.BeginReceive(s_byteMessage, 0, s_byteMessage.Length, SocketFlags.None, OnReceive, s_socket);
                }

                switch (msgReceived.Command)
                {
                    case Command.Register:
                        if (ClientNetworkEngineRegisterMessageEvent != null)
                        {
                            ClientNetworkEngineRegisterMessageEvent.Invoke(msgReceived.Message);
                        }
                        break;

                    case Command.AttemptLogin:
                        if (ClientNetworkEngineAttemptLoginErrorEvent != null)
                        {
                            ClientNetworkEngineAttemptLoginErrorEvent.Invoke(msgReceived.Message);
                        }
                        break;

                    case Command.Login:
                        if (msgReceived.ClientName == Client.Name)
                        {
                            if (ClientNetworkEngineLoggedinEvent != null)
                            {
                                ClientNetworkEngineLoggedinEvent.Invoke();
                            }
                            // Send Request for online client list
                            MessageStructure msgToSend = new MessageStructure
                            {
                                Command = Command.List,
                                ClientName = Client.Name
                            };
                            byte[] byteMessageToSend = msgToSend.ToByte();
                            s_socket.BeginSend(byteMessageToSend, 0, byteMessageToSend.Length, SocketFlags.None, OnSend, s_socket);
                            return;
                        }
                        if (ClientNetworkEngineLoginEvent != null)
                        {
                            ClientNetworkEngineLoginEvent.Invoke(msgReceived.ClientName, msgReceived.Message);
                        }
                        break;

                    case Command.List:
                        if (ClientNetworkEngineClientsListEvent != null)
                        {
                            ClientNetworkEngineClientsListEvent.Invoke(msgReceived.Message);
                        }
                        break;

                    case Command.Logout:
                        if (ClientNetworkEngineLogoutEvent != null)
                        {
                            ClientNetworkEngineLogoutEvent.Invoke(msgReceived.ClientName, msgReceived.Message);
                        }
                        break;

                    case Command.Message:
                        if (ClientNetworkEngineMessageEvent != null)
                        {
                            ClientNetworkEngineMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Message, ColorTranslator.FromHtml(msgReceived.Color));
                        }
                        break;

                    case Command.NameChange:
                        if (Client.Name == msgReceived.ClientName)
                        {
                            Client.Name = msgReceived.Message;
                        }
                        if (ClientNetworkEngineNameChangeEvent != null)
                        {
                            ClientNetworkEngineNameChangeEvent.Invoke(msgReceived.ClientName, msgReceived.Message, ColorTranslator.FromHtml(msgReceived.Color));
                        }
                        break;

                    case Command.ColorChanged:
                        if (ClientNetworkEngineColorChangedEvent != null)
                        {
                            ClientNetworkEngineColorChangedEvent.Invoke(msgReceived.ClientName, ColorTranslator.FromHtml(msgReceived.Color));
                        }
                        break;

                    case Command.PrivateStart:
                        if (ClientNetworkEnginePrivateChatStartEvent != null)
                        {
                            ClientNetworkEnginePrivateChatStartEvent.Invoke(msgReceived.ClientName);
                        }
                        break;

                    case Command.PrivateMessage:
                        if (ClientNetworkEnginePrivateMessageEvent != null)
                        {
                            ClientNetworkEnginePrivateMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Private, msgReceived.Message);
                        }
                        break;

                    case Command.PrivateStopped:
                        if (ClientNetworkEnginePrivateStoppedEvent != null)
                        {
                            ClientNetworkEnginePrivateStoppedEvent.Invoke(msgReceived.ClientName);
                        }
                        //TabPagePrivateChatReceiveClientEvent.Invoke(msgReceived.ClientName, msgReceived.Private, msgReceived.Message, 1);
                        break;

                    case Command.ServerMessage:
                        if (ClientNetworkEngineServerMessageEvent != null)
                        {
                            ClientNetworkEngineServerMessageEvent.Invoke(msgReceived.Message);
                        }
                        break;

                    case Command.ImageMessage:
                        MemoryStream ms = new MemoryStream(msgReceived.ImgByte);
                        Image img = Image.FromStream(ms);
                        if (ClientNetworkEngineImageMessageEvent != null)
                        {
                            ClientNetworkEngineImageMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Private, img);
                        }
                        break;
                }
            }
            //catch (ArgumentException)
            //{
            //    //MessageBox.Show(ex.Message + @" -> OnReceive", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + @" -> OnReceive", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 12
0
 private static void OnAttemptConnect(IAsyncResult ar)
 {
     try
     {
         Status = true;
         s_socket.EndConnect(ar); //notify the server the connection was established succefully
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.AttemptLogin,
             Color = HexConverter.Convert(Client.Color),
             ClientName = Client.Name,
             UserName = Client.UserName
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         // Ssend the login credinails of the established connection to the server
         //s_socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, null);
         s_socket.Send(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None);
         s_byteMessage = new byte[2097152];
         s_socket.BeginReceive(s_byteMessage, 0, s_byteMessage.Length, SocketFlags.None, OnReceive, null);
     }
     catch (Exception ex)
     {
         if (ClientNetworkEngineAttemptLoginErrorEvent != null)
         {
             ClientNetworkEngineAttemptLoginErrorEvent.Invoke(ex.Message);
         }
         //MessageBox.Show(ex.Message + @" -> OnAttemptConnect", @"Chat: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 13
0
 public static void StartPrivateChat(string clientNamePrivate)
 {
     try
     {
         MessageStructure msgToSend = new MessageStructure
         {
             UserName = Client.UserName,
             Command = Command.PrivateStart,
             ClientName = Client.Name,
             Private = clientNamePrivate
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         s_socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> StartPrivateChat", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 14
0
 public static void SendMessage(string message)
 {
     try
     {
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.Message,
             UserName = Client.UserName,
             ClientName = Client.Name,
             Color = HexConverter.Convert(Client.Color),
             Message = message
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         s_socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, null);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> SendMessage", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 15
0
        private static void ReceiveDeadLetterMode <T>(Channel channel, Action <T, BasicDeliverEventArgs> received, MessageStructure messageStructure)
        {
            var currentChannel             = channel.CurrentChannel;
            EventingBasicConsumer consumer = new EventingBasicConsumer(currentChannel);

            consumer.Received += (ch, ea) =>
            {
                var body = Encoding.UTF8.GetString(ea.Body);
                try
                {
                    channel.Logger.LogInformation($"{messageStructure.Queue.Name} Queue 消息体{{0}}", body);
                    var message = JsonConvert.DeserializeObject <T>(body);
                    try
                    {
                        received(message, ea);
                    }
                    catch (Exception e)
                    {
                        channel.Logger.LogError($"{messageStructure.Queue.Name} Queue 执行失败,原因:{{0}},消息体{{1}}", e, body);
                        currentChannel.BasicNack(ea.DeliveryTag, false, false);
                    }
                }
                catch (Exception)
                {
                    channel.Logger.LogError($"Json解析{typeof(T).Name}失败:{{0}}", body);
                    currentChannel.BasicNack(ea.DeliveryTag, false, false);
                }
            };
            currentChannel.BasicConsume(messageStructure.Queue.Name, false, consumer);
        }
Exemplo n.º 16
0
 protected override void OnCallRemote(string routePath, ActionGetter actionGetter, MessageStructure response)
 {
     base.OnCallRemote(routePath, actionGetter, response);
 }
Exemplo n.º 17
0
 /// <summary>
 /// init
 /// </summary>
 /// <param name="paramGetter"></param>
 /// <param name="response"></param>
 protected RemoteStruct(ActionGetter paramGetter, MessageStructure response)
 {
     this.paramGetter = paramGetter;
     this.response    = response;
 }
Exemplo n.º 18
0
        /// <summary>
        /// 处理循环记录
        /// </summary>
        /// <param name="respContent"></param>
        /// <param name="queue"></param>
        /// <param name="reader"></param>
        private static void ProcessLoopRocord(StringBuilder respContent, List <ParamInfoModel> queue, MessageStructure reader)
        {
            StringBuilder headContent    = new StringBuilder();
            StringBuilder builderContent = new StringBuilder();
            int           recordCount    = 0;

            try
            {
                recordCount = reader.ReadInt();
            }
            catch (Exception ex)
            {
            }
            respContent.Append("<tr>");
            respContent.Append("<td style=\"width:25%;\" align=\"left\">Record(N)</td>");
            respContent.Append("<td style=\"width:20%;\" align=\"left\">Record</td>");
            respContent.AppendFormat("<td style=\"width:50%;\" align=\"left\">{0}</td>", recordCount);
            respContent.Append("</tr>");

            respContent.Append("<tr><td colspan=\"3\" align=\"center\">");
            respContent.Append("<!--子表开始--><table style=\"width:98%; border-color:#999\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");
            if (recordCount == 0)
            {
                builderContent.Append("<tr><td align=\"center\">空数据</td></tr>");
            }


            for (int i = 0; i < recordCount; i++)
            {
                try
                {
                    reader.RecordStart();
                    MessageStructure msgReader = reader;
                    int loopDepth = 0; //循环深度
                    List <ParamInfoModel> recordQueue = new List <ParamInfoModel>();

                    headContent.Append("<tr><!--头开始tr-->");
                    builderContent.Append("<tr><!--内容开始tr-->");
                    int columnNum = 0;

                    #region

                    for (int r = 1; r < queue.Count - 1; r++)
                    {
                        var       record     = queue[r];
                        string    fieldName  = record.Field;
                        FieldType fieldType  = record.FieldType;
                        string    fieldValue = "";
                        try
                        {
                            if (loopDepth > 0 && fieldType == FieldType.End)
                            {
                                loopDepth--;
                                recordQueue.Add(record);
                            }
                            if (loopDepth == 0 && recordQueue.Count > 0)
                            {
                                builderContent.Append("</tr><tr>");
                                builderContent.AppendFormat("<td colspan=\"{0}\" align=\"right\">", columnNum);
                                builderContent.Append(
                                    "<!--子表开始--><table style=\"width:95%; border-color:#999\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");
                                //处理循环记录
                                ProcessLoopRocord(builderContent, recordQueue, msgReader);

                                builderContent.Append("</table><!--子表结束-->");
                                builderContent.Append("</td>");
                                recordQueue.Clear();
                            }

                            if (loopDepth == 0)
                            {
                                if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                                {
                                    if (i == 0)
                                    {
                                        headContent.AppendFormat("<td align=\"center\"><strong>{0}</strong>({1})</td>",
                                                                 fieldName, fieldType);
                                    }
                                    builderContent.AppendFormat("<td align=\"center\">&nbsp;{0}</td>", fieldValue);
                                    columnNum++;
                                }
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                    recordQueue.Add(record);
                                }
                            }
                            else if (fieldType != FieldType.End)
                            {
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                }
                                recordQueue.Add(record);
                            }
                        }
                        catch (Exception ex)
                        {
                            builderContent.AppendFormat("<td align=\"center\">{0}列出错{1}</td>", fieldName, ex.Message);
                        }
                    }

                    #endregion

                    headContent.Append("</tr><!--头结束tr-->");
                    builderContent.Append("</tr><!--内容结束tr-->");
                    //读取行结束
                    reader.RecordEnd();
                }
                catch (Exception ex)
                {
                    builderContent.AppendFormat("<tr><td align=\"left\">{0}行出错{1}</td></tr>", (i + 1), ex.Message);
                }
            }

            respContent.Append(headContent.ToString());
            respContent.Append(builderContent.ToString());
            respContent.Append("</table><!--子表结束-->");
            respContent.Append("</td></tr>");
            respContent.Append("<tr>");
            respContent.Append("<td colspan=\"3\" align=\"left\">End</td>");
            respContent.Append("</tr>");
        }
Exemplo n.º 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="session"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public byte[] Receive(string session, byte[] buffer)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            BufferReader reader      = new BufferReader(buffer);
            string       routeName   = "";
            string       paramString = reader.ReadPacketString();

#if DEBUG
            //todo trace
            TraceLog.ReleaseWrite("Tcp param:{0}", paramString);
#endif
            bool isRoute = false;
            if (!string.IsNullOrEmpty(paramString) && paramString.StartsWith("route:", StringComparison.CurrentCultureIgnoreCase))
            {
                //检查参数格式:route:name?d=param
                isRoute = true;
                string[] paramArray = paramString.Split('?');
                if (paramArray.Length == 2)
                {
                    routeName   = paramArray[0].Replace("route:", "");
                    paramString = "?" + paramArray[1];
                }
            }
            paramString = HttpUtility.UrlDecode(paramString, Encoding.UTF8);
            int index = paramString.IndexOf("?d=");
            if (index != -1)
            {
                index      += 3;
                paramString = paramString.Substring(index, paramString.Length - index);
            }
            var         paramGeter    = new ParamGeter(paramString);
            string      remoteAddress = session.RemoteAddress;
            MessageHead head          = ParseMessageHead(paramGeter);
            head.HasGzip     = true;
            session.UserData = head;
            MessageStructure ms = new MessageStructure();
#if DEBUG
            Console.WriteLine("{0}>>请求参数:MsgId:{1},ActionId:{2},ip:{3}", DateTime.Now.ToLongTimeString(),
                              head.MsgId, head.Action, remoteAddress);
#endif
            var settings = ParseRequestSettings(paramGeter, remoteAddress);
            settings.ParamString = paramString;
            settings.RouteName   = routeName;

            byte[]       sendBuffer = new byte[0];
            RequestError error      = RequestError.Success;
            try
            {
                if (isRoute)
                {
                    if (CheckCallAccessLimit(remoteAddress))
                    {
                        error          = RequestError.Unknown;
                        head.ErrorInfo = ErrorCallAccessLimit;
                    }
                    else
                    {
                        ServiceRequest.CallRemote(settings, out sendBuffer);
                    }
                }
                else
                {
                    ServiceRequest.Request(settings, out sendBuffer);
                }
            }
            catch (CommunicationObjectFaultedException fault)
            {
                TraceLog.WriteError("The wcfclient request faulted:{0}", fault);
                error = RequestError.Closed;
                ServiceRequest.ResetChannel(settings);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is SocketException)
                {
                    var sex = ex.InnerException as SocketException;
                    TraceLog.WriteError("The wcfclient request connect:{0}-{1}", sex.SocketErrorCode, sex);
                    if (sex.SocketErrorCode == SocketError.TimedOut)
                    {
                        error = RequestError.Timeout;
                    }
                    else
                    {
                        error = RequestError.UnableConnect;
                    }
                }
                else
                {
                    TraceLog.WriteError("The wcfclient request error:{0}", ex);
                    error = RequestError.Unknown;
                }
                ServiceRequest.ResetChannel(settings);
            }
            watch.Stop();
            switch (error)
            {
            case RequestError.Success:
                ms.WriteGzipBuffer(sendBuffer);

                string msg = string.Format("[{0}]请求响应{1}:route={8},MsgId={2},St={3},Action-{4},error:{5}-{6},bytes:{7},响应时间:{9}ms\r\n",
                                           DateTime.Now.ToLongTimeString(),
                                           session.RemoteAddress,
                                           head.MsgId,
                                           head.St,
                                           head.Action,
                                           head.ErrorCode,
                                           head.ErrorInfo,
                                           sendBuffer.Length,
                                           routeName,
                                           (int)watch.Elapsed.TotalMilliseconds);
                TraceLog.ReleaseWrite(msg);
#if DEBUG
#endif
                Console.WriteLine(msg);

                break;

            case RequestError.Closed:
            case RequestError.NotFindService:
                head.ErrorInfo = ErrorNotFind;
                DoWriteError(ms, head);
                break;

            case RequestError.UnableConnect:
                head.ErrorInfo = ErrorConnected;
                DoWriteError(ms, head);
                break;

            case RequestError.Timeout:
                head.ErrorInfo = ErrorTimeout;
                DoWriteError(ms, head);
                break;

            case RequestError.Unknown:
                DoWriteError(ms, head);
                break;

            default:
                throw new ArgumentOutOfRangeException("RequestError", error, "Not process RequestError enum.");
            }
            sendBuffer = ms.ReadBuffer();
            return(sendBuffer);
        }
Exemplo n.º 20
0
 /// <summary>
 ///
 /// </summary>
 public SocketGameResponse()
 {
     _buffers = new MessageStructure();
 }
Exemplo n.º 21
0
 public SignOut(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
 }
Exemplo n.º 22
0
 protected override void SuccessCallback(MessageStructure writer, MessageHead head)
 {
 }
Exemplo n.º 23
0
 public GateHandler(ActionGetter paramGtter, MessageStructure response)
     : base(paramGtter, response)
 {
 }
Exemplo n.º 24
0
 public MessageHead GetReadHeader(MessageStructure reader)
 {
     return(reader.ReadHeadGzip());
 }
Exemplo n.º 25
0
 public LWGetWorldSinglePvpRankHandler(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
 }
Exemplo n.º 26
0
 private static void PushChildStack(MessageStructure parent, SchemaColumn parentColumn, object value)
 {
     if (parentColumn.IsDictionary)
     {
         var     column = parentColumn.Children[1];
         dynamic dict   = value;
         dynamic keys   = dict.Keys;
         int     count  = dict.Count;
         parent.PushIntoStack(count);
         foreach (var key in keys)
         {
             object item       = dict[key];
             var    itemWriter = new MessageStructure();
             itemWriter.PushIntoStack(key);
             if (EntitySchemaSet.IsSupportType(column.ColumnType))
             {
                 itemWriter.PushIntoStack(column.ColumnType, item);
             }
             else if (column.HasChild)
             {
                 PushChildStack(itemWriter, column, item);
             }
             parent.PushIntoStack(itemWriter);
         }
     }
     else if (parentColumn.IsList)
     {
         var     column = parentColumn.Children[0];
         dynamic list   = value;
         int     count  = list.Count;
         parent.PushIntoStack(count);
         foreach (var item in list)
         {
             var itemWriter = new MessageStructure();
             if (EntitySchemaSet.IsSupportType(column.ColumnType))
             {
                 itemWriter.PushIntoStack(column.ColumnType, item);
             }
             else if (column.HasChild)
             {
                 PushChildStack(itemWriter, column, item);
             }
             parent.PushIntoStack(itemWriter);
         }
     }
     else
     {
         //child entity object
         parent.PushIntoStack(1);
         var typeAccessor = ObjectAccessor.Create(value, true);
         var itemWriter   = new MessageStructure();
         foreach (var column in parentColumn.Children)
         {
             try
             {
                 var fieldValue = typeAccessor[column.Name];
                 if (EntitySchemaSet.IsSupportType(column.ColumnType))
                 {
                     itemWriter.PushIntoStack(column.ColumnType, fieldValue);
                 }
                 else if (column.HasChild)
                 {
                     PushChildStack(itemWriter, column, fieldValue);
                 }
             }
             catch
             {
             }
         }
         parent.PushIntoStack(itemWriter);
     }
 }
Exemplo n.º 27
0
        private static void OnReceive(IAsyncResult ar)
        {
            //if (!s_serverEngineStatus) {
            //    return;
            //}
            try
            {
                // Casting the AsyncState to a socket class
                Socket receivedClientSocket = (Socket)ar.AsyncState;
                receivedClientSocket.EndReceive(ar);
                // Translating the array of received bytes to  an intelligent class MessageStructure
                MessageStructure msgReceived = new MessageStructure(sr_byteMessage);
                // Constract the initial details of new object MessageStructure which will be sent out
                MessageStructure msgToSend = new MessageStructure
                {
                    UserName = msgReceived.UserName,
                    Command = msgReceived.Command,
                    ClientName = msgReceived.ClientName,
                    Color = msgReceived.Color
                };
                // Create a new byte[] class which will filled in the following case switch statment
                byte[] messageBytes;
                switch (msgReceived.Command)
                {
                    case Command.Register:
                        msgToSend.Message = ServerDataEngine.Register(msgReceived.UserName, "Haven't logged in yet", "null", "Offline");
                        messageBytes = msgToSend.ToByte();
                        receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None);
                        return;

                    case Command.AttemptLogin:
                        if (sr_clientList.Any(client => client.Name == msgReceived.ClientName))
                        {
                            msgToSend.Message = "This Name already in use";
                            messageBytes = msgToSend.ToByte();
                            receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None);
                            receivedClientSocket.Close();
                            return;
                        }
                        if (ServerDataEngine.CheckIfRegistered(msgReceived.UserName) == 0)
                        {
                            msgToSend.Message = "No user found which matches this User name";
                            messageBytes = msgToSend.ToByte();
                            receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None);
                            receivedClientSocket.Close();
                            return;
                        }
                        if (ServerDataEngine.CheckStatus(msgReceived.UserName) == "Online")
                        {
                            msgToSend.Message = "This User Name already logged in";
                            messageBytes = msgToSend.ToByte();
                            receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None);
                            receivedClientSocket.Close();
                            return;
                        }

                        msgToSend.Command = Command.Login;
                        msgReceived.Command = Command.Login;
                        //messageBytes = msgToSend.ToByte();
                        //receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket);
                        goto case Command.Login;

                    case Command.Login:
                        // When the Login Command is received the ServerNetworkEngine will
                        // add that established connection (Socket) along
                        // with the provoided information to distinguish it (Name) to sr_clientList
                        // as a Client and sent the command Login to ohter clients to handle
                        // it on their end excluding the sending client
                        // and set the status of the new logged in client to online
                        Client newClient = new Client
                        {
                            UserName = msgReceived.UserName,
                            Name = msgReceived.ClientName,
                            Socket = receivedClientSocket,
                            Color = ColorTranslator.FromHtml(msgReceived.Color),
                            IpEndPoint = receivedClientSocket.RemoteEndPoint as IPEndPoint
                        };
                        // Adding the current handled established connection(client) to the connected _clientList
                        sr_clientList.Add(newClient);
                        // Setting the message to broadcast to all other clients
                        msgToSend.Message = "<<< " + newClient.Name + " has joined the room >>>";
                        ServerDataEngine.UpdateStatus(msgReceived.UserName, msgReceived.ClientName, "Online");
                        ServerDataEngine.UpdateDate(msgReceived.UserName, Time.NowTimeDate());
                        if (ServerNetworkEngineEngineClientToAddEvent != null)
                        {
                            ServerNetworkEngineEngineClientToAddEvent.Invoke(newClient.Name, newClient.IpEndPoint);
                        }
                        break;

                    case Command.Logout:
                        // When the Logout Command is received the ServerNetworkEngine will
                        // remove the the client from _clientList a long with all of
                        // it's information, socket/clientName etc..
                        // server engine will also stop listening to the removed socket
                        // and broadcast the message to all clients excluding the removed client
                        receivedClientSocket.Shutdown(SocketShutdown.Both);
                        receivedClientSocket.BeginDisconnect(true, (OnDisonnect), receivedClientSocket);
                        // Setting the message to broadcast to all other clients
                        msgToSend.Message = "<<< " + msgReceived.ClientName + " has just left the chat >>>";
                        // Removing client (established connection) _clientList
                        foreach (Client client in sr_clientList.Where(client => client.Socket == receivedClientSocket))
                        {
                            sr_clientList.Remove(client);
                            ServerDataEngine.UpdateStatus(client.UserName, msgReceived.ClientName, "Offline");
                            break;
                        }
                        if (ServerNetworkEngineClientToRemoveEvent != null)
                        {
                            ServerNetworkEngineClientToRemoveEvent.Invoke(msgReceived.ClientName);
                        }
                        break;

                    case Command.Disconnect:
                        receivedClientSocket.BeginDisconnect(true, (OnDisonnect), receivedClientSocket);
                        if (ServerNetworkEngineServerStopTickEvent != null)
                        {
                            ServerNetworkEngineServerStopTickEvent.Invoke(msgReceived.ClientName);
                        }
                        ServerDataEngine.UpdateStatus(msgReceived.UserName, msgReceived.ClientName, "Offline");
                        ++s_disconnectCout;
                        if (sr_clientList.Count == s_disconnectCout)
                        {
                            if (ServerNetworkEngineServerStoppedEvent != null)
                            {
                                ServerNetworkEngineServerStoppedEvent.Invoke();
                            }
                            ServerDataEngine.ResetStatus();
                        }
                        break;

                    case Command.List:
                        // when the List command received serverEngine will send the names of all the
                        // clients(established coneections) back to the requesting (client) (established connection)
                        msgToSend.Command = Command.List;
                        Client lastItem = sr_clientList[sr_clientList.Count - 1];
                        //msgToSend.ClientName = lastItem.Name;
                        foreach (Client client in sr_clientList)
                        {
                            //To keep things simple we use a marker to separate the user names
                            msgToSend.Message += client.Name + ",";
                        }
                        // Convert msgToSend to a bytearray representative, this is needed in order to send(broadcat) the message over the TCP protocol
                        messageBytes = msgToSend.ToByte();
                        // Send(broadcast) the name of the estalished connections(cleints) in the chat
                        receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket);
                        break;

                    case Command.Message:
                        // Set the message which will be broadcasted to all the connected clients
                        ServerDataEngine.AddMessage(msgReceived.UserName, msgReceived.Message, Time.NowTimeDate(), "false", "null");
                        msgToSend.Message = msgReceived.Message;
                        if (ServerNetworkEngineSendPublicMessageEvent != null)
                        {
                            ServerNetworkEngineSendPublicMessageEvent.Invoke(msgToSend.ClientName, ColorTranslator.FromHtml(msgReceived.Color), msgToSend.Message);
                        }
                        break;

                    case Command.NameChange:
                        foreach (Client client in sr_clientList.Where(client => client.Name == msgReceived.ClientName))
                        {
                            client.Name = msgReceived.Message;
                            break;
                        }
                        msgToSend.Message = msgReceived.Message;
                        if (ServerNetworkEngineClientNameChangedEvent != null)
                        {
                            ServerNetworkEngineClientNameChangedEvent.Invoke(msgReceived.ClientName, msgReceived.Message);
                        }
                        ServerDataEngine.UpdateLoggedLastLogged(msgReceived.ClientName, msgReceived.Message);
                        goto case Command.ColorChanged;

                    case Command.ColorChanged:
                        Color newColor = ColorTranslator.FromHtml(msgToSend.Color);
                        foreach (Client client in sr_clientList.Where(client => client.Name == msgReceived.ClientName))
                        {
                            client.Color = newColor;
                            break;
                        }
                        msgToSend.Message = msgReceived.Message;
                        if (ServerNetworkEngineClientColorChangedEvent != null)
                        {
                            ServerNetworkEngineClientColorChangedEvent.Invoke(msgReceived.ClientName, newColor);
                        }
                        break;

                    case Command.PrivateStart:
                        foreach (Client client in sr_clientList.Where(client => client.Name == msgReceived.Private))
                        {
                            msgToSend.Private = msgReceived.Private;
                            messageBytes = msgToSend.ToByte();
                            client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket);
                            if (ServerNetworkEnginePrivateChatStartedEvent != null)
                            {
                                ServerNetworkEnginePrivateChatStartedEvent.Invoke(msgReceived.ClientName, msgReceived.Private);
                            }
                            break;
                        }
                        break;

                    case Command.PrivateMessage:
                        foreach (Client client in sr_clientList.Where(clientLinq => clientLinq.Name == msgReceived.Private))
                        {
                            msgToSend.Private = msgReceived.Private;
                            msgToSend.Message = msgReceived.Message;
                            messageBytes = msgToSend.ToByte();
                            client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket);
                            receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket);
                            if (ServerNetworkEnginePrivateChatMessageEvent != null)
                            {
                                ServerNetworkEnginePrivateChatMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Private, msgReceived.Message);
                            }
                            ServerDataEngine.AddMessage(msgReceived.UserName, msgReceived.Message, Time.NowTimeDate(), client.UserName, "null");
                            break;
                        }
                        break;

                    case Command.PrivateStopped:
                        foreach (Client client in sr_clientList.Where(clientLinq => clientLinq.Name == msgReceived.Private))
                        {
                            msgToSend.Private = msgReceived.Private;
                            messageBytes = msgToSend.ToByte();
                            client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket);
                            receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket);
                        }
                        if (ServerNetworkEnginePrivateChatStoppedEvent != null)
                        {
                            ServerNetworkEnginePrivateChatStoppedEvent.Invoke(msgReceived.ClientName, msgReceived.Private);
                        }
                        break;

                    case Command.ImageMessage:
                        MemoryStream s_ms = new MemoryStream(msgReceived.ImgByte);
                        Image s_img = Image.FromStream(s_ms);
                        if (!Directory.Exists(@"Images\" + msgReceived.UserName))
                        {
                            Directory.CreateDirectory(@"Images\" + msgReceived.UserName);
                        }
                        if (msgReceived.Private != null)
                        {
                            if (ServerNetworkEngineImageMessageEvent != null)
                            {
                                ServerNetworkEngineImageMessageEvent.Invoke(s_img, msgReceived.ClientName, msgReceived.Private);
                            }
                            Task.Factory.StartNew(() =>
                            {
                                foreach (Client client in sr_clientList.Where(clientLinq => clientLinq.Name == msgReceived.Private))
                                {
                                    msgToSend.Private = msgReceived.Private;
                                    msgToSend.ImgByte = msgReceived.ImgByte;
                                    messageBytes = msgToSend.ToByte();
                                    client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket);
                                    receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket);
                                    ServerDataEngine.AddMessage(msgReceived.UserName, "null", Time.NowTimeDate(), client.UserName, @"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate() + @"-" + client.UserName);
                                    //s_img.Save(@"Images\" + msgReceived.Private + @"\" + Time.SaveTimeDate() + client.UserName + @".png");
                                    s_img.Save(@"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate() + @".png");
                                    break;
                                }
                            });
                            break;
                        }
                        if (ServerNetworkEngineImageMessageEvent != null)
                        {
                            ServerNetworkEngineImageMessageEvent.Invoke(s_img, msgReceived.ClientName, msgReceived.Private);
                        }
                        msgToSend.ImgByte = msgReceived.ImgByte;
                        messageBytes = msgToSend.ToByte();
                        Task.Factory.StartNew(() =>
                        {
                            foreach (Client client in sr_clientList)
                            {
                                client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket);
                                ServerDataEngine.AddMessage(msgReceived.UserName, "null", Time.NowTimeDate(), "false", @"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate());
                                s_img.Save(@"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate() + @".png");
                            }
                        });
                        break;
                }

                // Send(broadcast) the message to clients (established connections)
                Task.Factory.StartNew(() =>
                {
                    if (msgToSend.Command != Command.List && msgToSend.Command != Command.PrivateStart && msgToSend.Command != Command.PrivateMessage && msgToSend.Command != Command.PrivateStopped && msgToSend.Command != Command.Disconnect && msgToSend.Command != Command.ImageMessage)
                    {
                        messageBytes = msgToSend.ToByte();
                        foreach (Client client in sr_clientList)
                        {
                            //if (client.Socket != receivedClientSocket || msgToSend.Command != Command.Login) {
                            client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket);
                            //}
                        }
                    }
                });
                // Continue listneing to receivedClientSocket established connection(client)
                if (msgReceived.Command != Command.Logout && msgReceived.Command != Command.Disconnect && msgReceived.Command != Command.AttemptLogin && msgReceived.Command != Command.Register)
                {
                    receivedClientSocket.BeginReceive(sr_byteMessage, 0, sr_byteMessage.Length, SocketFlags.None, OnReceive, receivedClientSocket);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + @" -> OnReceive", @"Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    /// <summary>
    /// Gets Message object based on user input
    /// </summary>
    /// <returns>Message object</returns>
    private MessageStructure GetUserInput()
    {
        MessageStructure msg = new MessageStructure();
        msg.Attachments = new List<string>();

        if (!string.IsNullOrEmpty(fileUpload1.FileName))
        {
            fileUpload1.SaveAs(Request.MapPath(fileUpload1.FileName));
            msg.Attachments.Add(Request.MapPath(fileUpload1.FileName));
        }

        if (!string.IsNullOrEmpty(fileUpload2.FileName))
        {
            fileUpload2.SaveAs(Request.MapPath(fileUpload2.FileName));
            msg.Attachments.Add(Request.MapPath(fileUpload2.FileName));
        }

        if (!string.IsNullOrEmpty(fileUpload3.FileName))
        {
            fileUpload3.SaveAs(Request.MapPath(fileUpload3.FileName));
            msg.Attachments.Add(Request.MapPath(fileUpload3.FileName));
        }

        if (!string.IsNullOrEmpty(fileUpload4.FileName))
        {
            fileUpload4.SaveAs(Request.MapPath(fileUpload4.FileName));
            msg.Attachments.Add(Request.MapPath(fileUpload4.FileName));
        }

        if (!string.IsNullOrEmpty(fileUpload5.FileName))
        {
            fileUpload5.SaveAs(Request.MapPath(fileUpload5.FileName));
            msg.Attachments.Add(Request.MapPath(fileUpload5.FileName));
        }

        msg.Message = txtMessage.Text;
        msg.Subject = txtSubject.Text;
        msg.Group = chkGroup.Checked;
        msg.Addresses = this.GetList(txtPhone.Text);

        Session["CS_MessageToSend"] = msg;
        return msg;
    }
Exemplo n.º 29
0
 public static void ServerStop()
 {
     try
     {
         if (sr_clientList.Count == 0)
         {
             if (ServerNetworkEngineServerStoppedEvent != null)
             {
                 ServerNetworkEngineServerStoppedEvent.Invoke();
             }
             Status = false;
             s_serverSocket.Close();
             return;
         }
         Status = false;
         if (ServerNetworkEngineServerStopBeganEvent != null)
         {
             ServerNetworkEngineServerStopBeganEvent.Invoke(sr_clientList.Count);
         }
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.Disconnect
         };
         byte[] msgToSendByte = msgToSend.ToByte();
         Task.Factory.StartNew(() =>
         {
             foreach (Client client in sr_clientList)
             {
                 // Added only to slow down the progress bar advance for demonstration purposes
                 Thread.Sleep(150);
                 client.Socket.BeginSend(msgToSendByte, 0, msgToSendByte.Length, SocketFlags.None, OnSend, client.Socket);
             }
         });
         s_serverSocket.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + @" -> btnStopSrv_Click", @"Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 30
0
        private static void ReceiveRetryMode <T>(Channel channel, Action <T, BasicDeliverEventArgs> received, MessageStructure messageStructure)
        {
            var currentChannel             = channel.CurrentChannel;
            EventingBasicConsumer consumer = new EventingBasicConsumer(currentChannel);

            consumer.Received += (ch, ea) =>
            {
                var body = Encoding.UTF8.GetString(ea.Body);
                try
                {
                    channel.Logger.LogInformation($"{messageStructure.Queue.Name} Queue 消息体{{0}}", body);
                    var message = JsonConvert.DeserializeObject <T>(body);
                    try
                    {
                        received(message, ea);
                    }
                    catch (Exception e)
                    {
                        var  properties = ea.BasicProperties;
                        long retryCount = GetRetryCount(properties);
                        if (retryCount > 3)
                        {
                            IDictionary <String, Object> headers = new Dictionary <String, Object>();
                            headers.Add("x-orig-routing-key", GetOrigRoutingKey(properties, ea.RoutingKey));
                            var address = new PublicationAddress(ExchangeType.Direct, messageStructure.Exchange.DeadLetterName, messageStructure.RoutingKey);
                            channel.Publish(CreateOverrideProperties(properties, headers), ea.Body, address);
                        }
                        else
                        {
                            IDictionary <String, Object> headers = properties.Headers;
                            if (headers == null)
                            {
                                headers = new Dictionary <String, Object>();
                                headers.Add("x-orig-routing-key", GetOrigRoutingKey(properties, ea.RoutingKey));
                            }
                            else
                            {
                                headers["x-orig-routing-key"] = GetOrigRoutingKey(properties, ea.RoutingKey);
                            }
                            var address = new PublicationAddress(ExchangeType.Direct, messageStructure.Exchange.RetryName, messageStructure.RoutingKey);
                            channel.Publish(CreateOverrideProperties(properties, headers), ea.Body, address);
                        }
                    }
                }
                catch (Exception)
                {
                    channel.Logger.LogError($"Json解析{typeof(T).Name}失败:{{0}}", body);
                    var properties = ea.BasicProperties;
                    var address    = new PublicationAddress(ExchangeType.Direct, messageStructure.Exchange.DeadLetterName, messageStructure.RoutingKey);
                    channel.Publish(properties, ea.Body, address);
                }
            };
            currentChannel.BasicConsume(messageStructure.Queue.Name, true, consumer);
        }
Exemplo n.º 31
0
        private async System.Threading.Tasks.Task ProcessPackage(RequestPackage package, GameSession session)
        {
            if (package == null)
            {
                return;
            }

            try
            {
                ActionGetter actionGetter;
                byte[]       data = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    actionGetter = ActionDispatcher.GetActionGetter(package, session);
                    if (CheckRemote(package.RouteName, actionGetter))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, actionGetter, response);
                        data = response.PopBuffer();
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    SocketGameResponse response = new SocketGameResponse();
                    response.WriteErrorCallback += ActionDispatcher.ResponseError;
                    actionGetter = ActionDispatcher.GetActionGetter(package, session);
                    DoAction(actionGetter, response);
                    data = response.ReadByte();
                }
                try
                {
                    if (session != null && data.Length > 0)
                    {
                        byte   userRet = 0;
                        string userSid = string.Empty;
                        if (actionGetter.GetByte("UserRet", ref userRet) && userRet == (byte)1 &&
                            actionGetter.GetString("UserSid", ref userSid))
                        {
                            var switchSession = ServerSsMgr.GetSwitchSession();
                            //未连接上路由服,则发给大厅服,由大厅服转发
                            if (switchSession == null)
                            {
                                var    paramStr = "ActionId=100&MsgId=0&UserSid=" + userSid;
                                string sign     = SignUtils.EncodeSign(paramStr, RequestParam.SignKey);
                                paramStr += string.Format("&{0}={1}", "sign", sign);
                                var    postData   = Encoding.UTF8.GetBytes(string.Format("?d={0}", paramStr));
                                byte[] paramBytes = new byte[postData.Length + PackageReader.EnterChar.Length + data.Length];
                                Buffer.BlockCopy(postData, 0, paramBytes, 0, postData.Length);
                                Buffer.BlockCopy(PackageReader.EnterChar, 0, paramBytes, postData.Length, PackageReader.EnterChar.Length);
                                Buffer.BlockCopy(data, 0, paramBytes, postData.Length + PackageReader.EnterChar.Length, data.Length);

                                await session.SendAsync(actionGetter.OpCode, paramBytes, 0, paramBytes.Length, OnSendCompleted);
                            }
                            //已连接上路由服,则直接发给路由服
                            else
                            {
                                var    paramStr = "ActionId=101&MsgId=0&UserSid=" + userSid;
                                string sign     = SignUtils.EncodeSign(paramStr, RequestParam.SignKey);
                                paramStr += string.Format("&{0}={1}", "sign", sign);
                                var    postData   = Encoding.UTF8.GetBytes(string.Format("?d={0}", paramStr));
                                byte[] paramBytes = new byte[postData.Length + PackageReader.EnterChar.Length + data.Length];
                                Buffer.BlockCopy(postData, 0, paramBytes, 0, postData.Length);
                                Buffer.BlockCopy(PackageReader.EnterChar, 0, paramBytes, postData.Length, PackageReader.EnterChar.Length);
                                Buffer.BlockCopy(data, 0, paramBytes, postData.Length + PackageReader.EnterChar.Length, data.Length);

                                await switchSession.SendAsync(actionGetter.OpCode, paramBytes, 0, paramBytes.Length, OnSendCompleted);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("PostSend error:{0}", ex);
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Task error:{0}", ex);
            }
            finally
            {
                if (session != null)
                {
                    session.ExitSession();
                }
            }
        }
Exemplo n.º 32
0
        private static void ProcessResult(List <ParamInfoModel> paramList, int contractId, StringBuilder respContent, MessageHead msg, MessageStructure msgReader, out string sid, out string uid, out string st)
        {
            sid = "";
            uid = "";
            st  = msg.St;
            ResponseHead(contractId, respContent, msg.ErrorCode, msg.ErrorInfo, msg.St);

            //AccountServer Error
            if (msg.ErrorCode < ErrorCode && msg.ErrorCode != 105 && msg.ErrorCode != 106)
            {
                //消息体
                respContent.AppendFormat("<h3>{0}-{1}</h3>", contractId, "返回结果");
                respContent.Append("<table style=\"width:99%; border-color:#f0f0f0\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
                respContent.Append("<tr><td style=\"width:15%;\"><strong>参数</strong></td><td style=\"width:10%;\"><strong>类型</strong></td>");
                respContent.Append("<td style=\"width:75%;\"><strong>参数值</strong></td></tr>");
                int loopDepth = 0;//循环深度
                List <ParamInfoModel> recordQueue = new List <ParamInfoModel>();
                #region 循环体
                foreach (var record in paramList)
                {
                    if (record.FieldType == FieldType.Void)
                    {
                        continue;
                    }
                    string    fieldName  = record.Field;
                    FieldType fieldType  = record.FieldType;
                    string    fieldValue = "";
                    try
                    {
                        if (loopDepth > 0 && fieldType == FieldType.End)
                        {
                            loopDepth--;
                            recordQueue.Add(record);
                        }
                        if (loopDepth == 0 && recordQueue.Count > 0)
                        {
                            //处理循环记录
                            ProcessLoopRocord(respContent, recordQueue, msgReader);
                            recordQueue.Clear();
                        }

                        if (loopDepth == 0)
                        {
                            if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                            {
                                //自动登录
                                if (NetHelper.LoginActionId.IndexOf(contractId.ToString(), StringComparison.OrdinalIgnoreCase) != -1)
                                {
                                    if ("SessionID".Equals(fieldName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        sid = fieldValue;
                                    }
                                    if ("UserID".Equals(fieldName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        uid = fieldValue;
                                    }
                                }
                                respContent.Append("<tr>");
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldName);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldType);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldValue);
                                respContent.Append("</tr>");
                            }
                            if (fieldType == FieldType.Record || fieldType == FieldType.SigleRecord)
                            {
                                loopDepth++;
                                recordQueue.Add(record);
                            }
                        }
                        else if (fieldType != FieldType.End)
                        {
                            if (fieldType == FieldType.Record || fieldType == FieldType.SigleRecord)
                            {
                                loopDepth++;
                            }
                            recordQueue.Add(record);
                        }
                    }
                    catch (Exception ex)
                    {
                        respContent.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", fieldName, fieldType, ex.ToString());
                    }
                }
                #endregion

                respContent.Append("</table>");
            }
        }
Exemplo n.º 33
0
 /// <summary>
 /// Call remote method
 /// </summary>
 /// <param name="routePath"></param>
 /// <param name="actionGetter"></param>
 /// <param name="response"></param>
 protected virtual void OnCallRemote(string routePath, ActionGetter actionGetter, MessageStructure response)
 {
     try
     {
         string[] mapList   = routePath.Split('.');
         string   funcName  = "";
         string   routeName = routePath;
         if (mapList.Length > 1)
         {
             funcName  = mapList[mapList.Length - 1];
             routeName = string.Join("/", mapList, 0, mapList.Length - 1);
         }
         string      routeFile = "";
         int         actionId  = actionGetter.GetActionId();
         MessageHead head      = new MessageHead(actionId);
         if (!ScriptEngines.SettupInfo.DisablePython)
         {
             routeFile = string.Format("Remote.{0}", routeName);
             dynamic scope = ScriptEngines.ExecutePython(routeFile);
             if (scope != null)
             {
                 var funcHandle = scope.GetVariable <RemoteHandle>(funcName);
                 if (funcHandle != null)
                 {
                     funcHandle(actionGetter, head, response);
                     response.WriteBuffer(head);
                     return;
                 }
             }
         }
         string typeName = string.Format(GameEnvironment.Setting.RemoteTypeName, routeName);
         routeFile = string.Format("Remote.{0}", routeName);
         var args     = new object[] { actionGetter, response };
         var instance = (object)ScriptEngines.Execute(routeFile, typeName, args);
         if (instance is RemoteStruct)
         {
             var target = instance as RemoteStruct;
             target.DoRemote();
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("OnCallRemote error:{0}", ex);
     }
 }
Exemplo n.º 34
0
        //protected override void DoListen()
        //{
        //    this.ServiceProxy.Listen(9001);
        //}

        protected override void OnCallRemote(string route, HttpGet httpGet, MessageHead head, MessageStructure structure)
        {
        }
Exemplo n.º 35
0
 public UpdateUserDataService(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
     IsNotRespond = true;
 }
Exemplo n.º 36
0
        private static void ProcessResult(int contractId, int slnId, StringBuilder respContent, MessageHead msg, MessageStructure msgReader, out string sid, out string uid)
        {
            sid = "";
            uid = "";
            //头部消息
            respContent.AppendFormat("<h3>{0}-{1}</h3>", contractId, "基本消息");
            respContent.Append("<table style=\"width:90%; border-color:#999\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
            respContent.Append("<tr><td style=\"width:25%;\"><strong>状态值</strong></td>");
            respContent.Append("<td style=\"width:75%;\"><strong>描述</strong></td></tr>");
            respContent.AppendFormat("<tr><td>{0}</td>", msg.ErrorCode);
            respContent.AppendFormat("<td>{0}&nbsp;</td></tr>", msg.ErrorInfo);
            respContent.Append("</table>");


            if (msg.ErrorCode != ErrorCode)
            {
                var respRecords = GetResponseFields(contractId, slnId);

                //消息体
                respContent.AppendFormat("<h3>{0}-{1}</h3>", contractId, "返回结果");
                respContent.Append("<table style=\"width:90%; border-color:#999\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
                respContent.Append("<tr><td style=\"width:15%;\"><strong>参数</strong></td><td style=\"width:10%;\"><strong>类型</strong></td>");
                respContent.Append("<td style=\"width:75%;\"><strong>参数值</strong></td></tr>");
                int loopDepth = 0;//循环深度
                List <ParamInfoModel> recordQueue = new List <ParamInfoModel>();
                #region 循环体
                foreach (var record in respRecords)
                {
                    string    fieldName  = record.Field;
                    FieldType fieldType  = record.FieldType;
                    string    fieldValue = "";
                    try
                    {
                        if (loopDepth > 0 && fieldType == FieldType.End)
                        {
                            loopDepth--;
                            recordQueue.Add(record);
                        }
                        if (loopDepth == 0 && recordQueue.Count > 0)
                        {
                            //处理循环记录
                            ProcessLoopRocord(respContent, recordQueue, msgReader);
                            recordQueue.Clear();
                        }

                        if (loopDepth == 0)
                        {
                            if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                            {
                                //自动登录
                                if (NetHelper.LoginActionId == contractId)
                                {
                                    if ("SessionID".Equals(fieldName))
                                    {
                                        sid = fieldValue;
                                    }
                                    if ("UserID".Equals(fieldName))
                                    {
                                        uid = fieldValue;
                                    }
                                }
                                respContent.Append("<tr>");
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldName);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldType);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldValue);
                                respContent.Append("</tr>");
                            }
                            if (fieldType == FieldType.Record)
                            {
                                loopDepth++;
                                recordQueue.Add(record);
                            }
                        }
                        else if (fieldType != FieldType.End)
                        {
                            if (fieldType == FieldType.Record)
                            {
                                loopDepth++;
                            }
                            recordQueue.Add(record);
                        }
                    }
                    catch (Exception ex)
                    {
                        respContent.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", fieldName, fieldType, ex.ToString());
                    }
                }
                #endregion

                respContent.Append("</table>");
            }
        }
 public LWCancelSinglePvpMatchingHandler(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
 }
Exemplo n.º 38
0
        private void OnHttpRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                listener.BeginGetContext(OnHttpRequest, listener);

                RequestPackage package;
                if (!ActionDispatcher.TryDecodePackage(context, out package))
                {
                    return;
                }

                GameSession session;
                if (package.ProxySid != Guid.Empty)
                {
                    session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                    session.ProxySid = package.ProxySid;
                }
                else
                {
                    session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
                }
                package.Bind(session);

                ActionGetter httpGet = ActionDispatcher.GetActionGetter(package, session);
                if (package.IsUrlParam)
                {
                    httpGet["UserHostAddress"] = session.RemoteAddress;
                    httpGet["ssid"]            = session.KeyCode.ToString("N");
                    httpGet["http"]            = "1";
                }

                var httpresponse = new SocketGameResponse();
                httpresponse.WriteErrorCallback += new ScutActionDispatcher().ResponseError;

                var clientConnection = new HttpClientConnection
                {
                    Context      = context,
                    Session      = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                var section = GetSection();
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, section.HttpRequestTimeout, Timeout.Infinite);
                byte[] respData = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    if (CheckRemote(package.RouteName, httpGet))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, httpGet, response);
                        respData = response.PopBuffer();
                    }
                }
                else
                {
                    DoAction(httpGet, httpresponse);
                    respData = httpresponse.ReadByte();
                }
                OnHttpResponse(clientConnection, respData, 0, respData.Length);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnHttpRequest error:{0}", ex);
            }
        }
Exemplo n.º 39
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     _session.Context.UserId = reader.ReadInt();
     return(true);
 }
Exemplo n.º 40
0
 public ChatService(ActionGetter paramGetter, MessageStructure response)
     : base(paramGetter, response)
 {
     IsNotRespond = true;
 }
Exemplo n.º 41
0
 protected override void SuccessCallback(MessageStructure writer, MessageHead head)
 {
     result = writer.ReadString();
 }
Exemplo n.º 42
0
        public static bool GetFieldValue(MessageStructure ms, FieldType fieldType, ref string val)
        {
            bool result = false;

            switch (fieldType)
            {
            case FieldType.Int:
                val    = ms.ReadInt().ToString();
                result = true;
                break;

            case FieldType.Password:
            case FieldType.String:
                val    = ms.ReadString();
                result = true;
                break;

            case FieldType.Short:
                val    = ms.ReadShort().ToString();
                result = true;
                break;

            case FieldType.Byte:
                val    = ms.ReadByte().ToString();
                result = true;
                break;

            case FieldType.Long:
                val    = ms.ReadLong().ToString();
                result = true;
                break;

            case FieldType.Bool:
                val    = ms.ReadBool().ToString();
                result = true;
                break;

            case FieldType.Float:
                val    = ms.ReadFloat().ToString();
                result = true;
                break;

            case FieldType.Double:
                val    = ms.ReadDouble().ToString();
                result = true;
                break;

            case FieldType.DateTime:
                val    = ms.ReadDateTime().ToString();
                result = true;
                break;

            case FieldType.ULong:
                val    = ms.ReadUInt64().ToString();
                result = true;
                break;

            case FieldType.UInt:
                val    = ms.ReadUInt32().ToString();
                result = true;
                break;

            case FieldType.UShort:
                val    = ms.ReadUInt16().ToString();
                result = true;
                break;

            case FieldType.Record:
                break;

            case FieldType.SigleRecord:
                break;

            case FieldType.End:
                break;

            case FieldType.Void:
                break;

            default:
                break;
            }

            return(result);
        }
Exemplo n.º 43
0
 public static void Disconnect()
 {
     try
     {
         if (!Status)
         {
             return;
         }
         Status = false;
         MessageStructure msgToSend = new MessageStructure
         {
             Command = Command.Logout,
             UserName = Client.UserName,
             ClientName = Client.Name
         };
         byte[] b = msgToSend.ToByte();
         s_socket.Send(b, 0, b.Length, SocketFlags.None);
         s_socket.Shutdown(SocketShutdown.Both);
         s_socket.BeginDisconnect(true, (OnDisonnect), s_socket);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message + " -> Disconnect", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }