Exemplo n.º 1
0
        //窗口关闭
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (bConnect)
            {
                try
                {
                    //发送断开连接信息
                    MsgEntity msg       = new MsgEntity(Constant.MSG_TYPE_CMD, Constant.SESSION_CODE_EXIT);
                    byte[]    sendbytes = FileUtils.GetSendBytes(msg);
                    sendUdpClient.Send(sendbytes, sendbytes.Length);
                }
                catch { }
            }

            if (receiveThread != null)
            {
                receiveThread.Abort();
            }
            if (sendUdpClient != null)
            {
                sendUdpClient.Close();
            }

            //写入配置文件
            WriteConfig();
        }
Exemplo n.º 2
0
        public JsonResult EditDict(string data)
        {
            T_Sys_Dict dict = JsonHelper.ConvertJsonString2Object <T_Sys_Dict>(data);
            MsgEntity  me   = dictService.EditDict(dict);

            return(this.Json(me, JsonRequestBehavior.DenyGet));
        }
Exemplo n.º 3
0
        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public MsgEntity AddDict(T_Sys_Dict dict)
        {
            MsgEntity me = new MsgEntity();

            if (dict == null || string.IsNullOrEmpty(dict.DICT_CODE))
            {
                me.MsgCode = MsgEntity.MsgCodeEnum.Failure;
                me.MsgDes  = "字典编码不能为空";
                return(me);
            }
            //查找关键字是否有相同值
            int count = dao.Count <T_Sys_Dict>(Predicates.Field <T_Sys_Dict>(f => f.DICT_CODE, Operator.Eq, dict.DICT_CODE));

            if (count > 0)
            {
                me.MsgCode = MsgEntity.MsgCodeEnum.Failure;
                me.MsgDes  = "字典编码重复";
                return(me);
            }
            dynamic result = dao.Insert <T_Sys_Dict>(dict);

            if (result != null)
            {
                me.MsgCode = MsgEntity.MsgCodeEnum.Success;
                me.MsgDes  = MsgEntity.MsgCodeEnum.Success.GetDescription();
            }
            return(me);
        }
Exemplo n.º 4
0
        private void skinButton_send_Click(object sender, EventArgs e)
        {
            if (this.textBoxSend.Text.Trim() == "")
            {
                return;
            }
            MsgEntity chatContract = new MsgEntity();

            chatContract.SenderID   = Common.CurrentUser.ID;
            chatContract.Reciver    = this.friend.ID;
            chatContract.MsgContent = this.textBoxSend.Text;
            chatContract.SendTime   = DateTime.Now;
            chatContract.IsWebMsg   = true;
            Common.TcpConn.SendObject("ChatMessage", chatContract);

            DateTime showTime = DateTime.Now;

            this.rtfRichTextBox_history.AppendTextAsRtf(string.Format("{0}  {1}\n", "我", showTime), new Font(this.Font, FontStyle.Regular), RtfRichTextBox.RtfColor.Blue);

            //this.rtfRichTextBox_history.AppendText(string.Format("{0}  {1}\n", "我", showTime));

            //this.rtfRichTextBox_history.AppendText("adsfasdf");
            this.rtfRichTextBox_history.AppendText(textBoxSend.Text);
            this.rtfRichTextBox_history.AppendText("\n");
            this.rtfRichTextBox_history.ScrollToCaret();
            this.textBoxSend.Clear();
            this.textBoxSend.Focus();
        }
Exemplo n.º 5
0
        /// <summary>
        /// 保存消息 左进
        /// </summary>
        private Task SaveMsg(string channel, MsgEntity msg)
        {
            var key = $"msgs_{channel}";

            return(_redisHelper.ListLeftPushAsync(key, msg));
            //_redisHelper.KeyExpire(key, TimeSpan.FromDays(7));
        }
Exemplo n.º 6
0
        //接收消息
        public void ReciveMessage(MsgEntity msg)// string From, DateTime Time, string Content, bool Self)
        {
            MsgType mt = (MsgType)msg.MsgType;

            switch (mt)
            {
            case MsgType.文字:
                this.AppendMessage("网页用户的消息", RtfRichTextBox.RtfColor.Blue, DateTime.Now, msg.MsgContent, true);
                break;

            case MsgType.震动:
                this.AppendMessage(msg.SenderName, RtfRichTextBox.RtfColor.Blue, msg.SendTime, Environment.NewLine + msg.SenderName + "给您" + msg.MsgContent + Environment.NewLine, false);
                //Vibration();
                break;

            case MsgType.文件:
                break;

            case MsgType.语音:
                break;

            case MsgType.视频:
                break;

            default:
                break;
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _btnSendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                var content = _txtMsg.Text;
                _txtMsg.Text = "";
                if (!string.IsNullOrWhiteSpace(content))
                {
                    content = new MsgEntity
                    {
                        MsgId    = Guid.NewGuid().ToString().Replace("-", "").ToLower(),
                        Type     = (int)MsgTypeEnum.文本,
                        Data     = content,
                        FromId   = _userId,
                        FromName = ""
                    }.JsonSerialize();

                    _webSocketHelper?.SendMsg(content);
                }
            }
            catch (Exception exception)
            {
                //Console.WriteLine(exception);
                //throw;
                ShowMsg("发送消息出错:" + exception.Message);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _btnAddUser_Click(object sender, EventArgs e)
        {
            var name = _txtAddUserName.Text.Trim();

            if (!string.IsNullOrWhiteSpace(name) && Regex.IsMatch(name, "^[a-zA-z\u4e00-\u9fa5]+$") && _userList.Count(t => t.UserName == name) == 0)
            {
                var newUserId = Guid.NewGuid().ToString().Replace("-", "").ToLower();

                var content = new MsgEntity
                {
                    Type   = (int)MsgTypeEnum.请求添加好友,
                    Data   = name,
                    FromId = _userId,
                    ToId   = newUserId
                }.JsonSerialize();

                //WebSocket发送消息
                _webSocketHelper.SendMsg(content);

                ShowMsg(_sysId, $"你发送消息请求添加[{name}]为好友,默认直接添加好友");


                _userList.Add(new UserEntity()
                {
                    UserId      = newUserId,
                    UserName    = name,
                    DisplayName = $"{name}"
                });
            }
        }
Exemplo n.º 9
0
        public JsonResult EditDictItem(T_Sys_DictItem dictItem)
        {
            //T_Sys_DictItem dictItem = JsonHelper.ConvertJsonString2Object<T_Sys_DictItem>(data);
            MsgEntity me = dictService.EditDictItem(dictItem);

            return(this.Json(me, JsonRequestBehavior.DenyGet));
        }
Exemplo n.º 10
0
        /// <summary>
        /// 好友数据、历史消息
        /// </summary>
        /// <param name="client"></param>
        private async void GetUserAndMsgList(IClient client)
        {
            var userListStr = await _redisMessageManage.GetUserList();

            var userListMsg = new MsgEntity
            {
                MsgId   = Guid.NewGuid().ToString().Replace("-", "").ToLower(),
                Type    = (int)MsgTypeEnum.获取好友数据,
                Data    = userListStr.JsonSerialize(),
                CurTime = DateTime.Now.ConvertDateTimeToInt(),
                FromId  = client.ClientId,
                ToId    = string.Empty
            };

            client.Socket?.Send(new [] { userListMsg }.JsonSerialize());


            var msgList = await _redisMessageManage.GetMsgList(client.ClientId);

            msgList = msgList.OrderBy(t => t.CurTime).ToList();
            foreach (var msg in msgList)
            {
                client.Socket?.Send(new[] { msg }.JsonSerialize());
            }
            await _redisMessageManage.DelAllMsg(client.ClientId);

            //while (true)
            //{
            //    Thread.Sleep(5);
            //    var msg = await _redisMessageManage.GetNextMsg(client.ClientId);
            //    if (msg == null || client.Socket == null) break;
            //    client.Socket?.Send(msg.JsonSerialize());
            //}
        }
Exemplo n.º 11
0
        /// <summary>
        /// Handle an incoming network message by passing the message to the EntityNetworkManager
        /// and handling the parsed result.
        /// </summary>
        /// <param name="msg">Incoming raw network message</param>
        public void HandleEntityNetworkMessage(MsgEntity msg)
        {
            if (!Started)
            {
                var incomingEntity = ProcessNetMessage(msg);
                if (incomingEntity.Message.Type != EntityMessageType.Error)
                {
                    MessageBuffer.Enqueue(incomingEntity);
                }
            }
            else
            {
                ProcessMsgBuffer();
                var incomingEntity = ProcessNetMessage(msg);

                // bad message or handled by something else
                if (incomingEntity == null)
                {
                    return;
                }

                if (!Entities.ContainsKey(incomingEntity.Message.EntityUid))
                {
                    MessageBuffer.Enqueue(incomingEntity);
                }
                else
                {
                    Entities[incomingEntity.Message.EntityUid].HandleNetworkMessage(incomingEntity);
                }
            }
        }
Exemplo n.º 12
0
        public static void SendMsg(string content, MsgType msgType, MsgSendType sendType, string reciverid, string reciverName, IList <ImageWrapper> imageWrapperList = null)
        {
            try
            {
                MsgEntity chatContract = new MsgEntity();
                chatContract.SenderID    = Common.CurrentUser.ID;
                chatContract.SenderName  = Common.CurrentUser.DisplayName;
                chatContract.Reciver     = reciverid;
                chatContract.ReciverName = reciverName;
                chatContract.MsgContent  = content;
                chatContract.SendTime    = DateTime.Now;
                chatContract.ImageList   = imageWrapperList;
                chatContract.MsgSendType = (int)sendType;
                chatContract.MsgType     = (int)msgType;

                //从客户端 Common中获取相应连接
                Connection p2pConnection = Common.GetUserConn(reciverid);
                if (p2pConnection != null)
                {
                    p2pConnection.SendObject("ClientChatMessage", chatContract);
                }
                else
                {
                    if (Common.TcpConn != null)
                    {
                        Common.TcpConn.SendObject("ChatMessage", chatContract);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 13
0
        private void DispatchEntityNetworkMessage(MsgEntity message)
        {
            // Don't try to retrieve the session if the client disconnected
            if (!message.MsgChannel.IsConnected)
            {
                return;
            }

            var player = _playerManager.GetSessionByChannel(message.MsgChannel);

            if (message.Sequence != 0)
            {
                if (_lastProcessedSequencesCmd[player] < message.Sequence)
                {
                    _lastProcessedSequencesCmd[player] = message.Sequence;
                }
            }

            switch (message.Type)
            {
            case EntityMessageType.ComponentMessage:
                ReceivedComponentMessage?.Invoke(this, new NetworkComponentMessage(message, player));
                return;

            case EntityMessageType.SystemMessage:
                var msg         = message.SystemMessage;
                var sessionType = typeof(EntitySessionMessage <>).MakeGenericType(msg.GetType());
                var sessionMsg  = Activator.CreateInstance(sessionType, new EntitySessionEventArgs(player), msg) !;
                ReceivedSystemMessage?.Invoke(this, sessionMsg);
                return;
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Handle an incoming network message by passing the message to the EntityNetworkManager
        /// and handling the parsed result.
        /// </summary>
        /// <param name="msg">Incoming raw network message</param>
        private void HandleEntityNetworkMessage(MsgEntity msg)
        {
            var incomingEntity = EntityNetworkManager.HandleEntityNetworkMessage(msg);

            // bad message or handled by something else
            if (incomingEntity == null)
            {
                return;
            }

            if (!Started)
            {
                if (incomingEntity.Message.Type != EntityMessageType.Error)
                {
                    MessageBuffer.Enqueue(incomingEntity);
                }
                return;
            }

            if (!Entities.TryGetValue(incomingEntity.Message.EntityUid, out var entity))
            {
                MessageBuffer.Enqueue(incomingEntity);
            }
            else
            {
                entity.HandleNetworkMessage(incomingEntity);
            }
        }
Exemplo n.º 15
0
 public IncomingEntityMessage(MsgEntity message)
 {
     Message = message;
     LastProcessingAttempt = DateTime.Now;
     ReceivedTime          = DateTime.Now;
     Expires = 30;
 }
Exemplo n.º 16
0
        public JsonResult Add(T_EC_KeyWords keyword)
        {
            keyword.ID = RandomHelper.GetUUID();
            MsgEntity me = _keywordService.Add(keyword);

            return(Json(me, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 17
0
 public void HandleSystemMessage(MsgEntity sysMsg)
 {
     foreach (var current in SystemMessageTypes.Where(x => x.Key == sysMsg.SystemMessage.GetType()))
     {
         current.Value.HandleNetMessage(sysMsg.MsgChannel, sysMsg.SystemMessage);
     }
 }
Exemplo n.º 18
0
        //窗体关闭
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (bListen && remoteIpEndPoint != null)
            {
                try
                {
                    //发送断开连接信息
                    MsgEntity msg       = new MsgEntity(Constant.MSG_TYPE_CMD, Constant.SESSION_CODE_EXIT);
                    byte[]    sendbytes = FileUtils.GetSendBytes(msg);
                    SendByteData(sendbytes);
                }
                catch { }
            }

            if (receiveThread != null)
            {
                receiveThread.Abort();
            }

            if (receiveUpdClient != null)
            {
                receiveUpdClient.Close();
            }

            //写入配置文件
            WriteConfig();
        }
Exemplo n.º 19
0
        public JsonResult Add(T_EC_KWCategory category)
        {
            category.ID = RandomHelper.GetUUID();
            MsgEntity me = _categoryService.Add(category);

            return(Json(me, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 20
0
        /// <summary>
        /// 发送文件
        /// </summary>
        /// <param name="param">续传断点</param>
        private void SendFile(object param)
        {
            long   breakpoint = Convert.ToInt64(param);
            string srcFile    = InvokeCtrl.GetCtrlText(txtFile);
            string hashcode   = FileUtils.GetHashCode(srcFile);
            string filename   = FileUtils.GetFileName(srcFile);

            totalBytes = FileUtils.GetFileSize(srcFile);

            if (totalBytes - breakpoint <= 0)
            {
                return;
            }
            //间歇时间
            Thread.Sleep(interval);

            MsgEntity msg = new MsgEntity();

            msg.msgType = Constant.MSG_TYPE_CMD;
            msg.msgBody = Constant.CMD_FILE_TRANSFER_REQ;
            msg.args    = new Dictionary <string, object>();
            msg.args.Add("filename", filename);       //文件名
            msg.args.Add("hashcode", hashcode);       //文件hash值
            msg.args.Add("total", totalBytes);        //文件大小
            msg.args.Add("reseed", (breakpoint > 0)); //是否为续传
            msg.args.Add("sendstate", "");            //传输状态(发送中/发送结束)
            msg.args.Add("offset", 0);                //传输流的偏移量

            int size = buffersize * 1024;

            if (breakpoint + size > totalBytes)
            {
                msg.args["sendstate"] = Constant.STATE_SEND_END;
                timerSendState.Stop();
            }
            else
            {
                msg.args["sendstate"] = Constant.STATE_SEND_ON;
            }

            msg.args["offset"] = breakpoint;

            byte[] extendData = FileUtils.ReadFromFile(srcFile, size, breakpoint);
            byte[] sendbytes  = FileUtils.GetSendBytes(msg, extendData);

            SendByteData(sendbytes);
            if (chkShowLog.Checked)
            {
                Log("发送文件流len=" + sendbytes.Length);
            }

            completeBytes += extendData.Length;

            int finish = (int)Math.Ceiling(100.0 * completeBytes / totalBytes);

            InvokeCtrl.UpdatePrgBarValue(prgBar1, finish, Color.FromKnownColor(KnownColor.Highlight), string.Format("发送完成{0} %", finish));

            InvokeCtrl.UpdateCtrlText(lbFinish, FileUtils.getFinished(completeBytes, totalBytes));
        }
Exemplo n.º 21
0
 public static void AddUserMsg(MsgEntity contract)
 {
     if (!chatMsgDic.ContainsKey(contract.SenderID))
     {
         chatMsgDic.Add(contract.SenderID, new List <MsgEntity>());
     }
     chatMsgDic[contract.SenderID].Add(contract);
 }
Exemplo n.º 22
0
        public NetworkComponentMessage(MsgEntity netMsg)
        {
            DebugTools.Assert(netMsg.Type == EntityMessageType.ComponentMessage);

            Channel   = netMsg.MsgChannel;
            EntityUid = netMsg.EntityUid;
            NetId     = netMsg.NetId;
            Message   = netMsg.ComponentMessage;
        }
Exemplo n.º 23
0
 private void ProcessEntityMessage(MsgEntity msgEntity)
 {
     switch (msgEntity.Type)
     {
     case EntityMessageType.ComponentMessage:
         DispatchComponentMessage(msgEntity);
         break;
     }
 }
Exemplo n.º 24
0
        public JsonResult AddDict(string data)
        {
            T_Sys_Dict dict = JsonHelper.ConvertJsonString2Object <T_Sys_Dict>(data);

            dict.ID = RandomHelper.GetUUID();
            MsgEntity me = dictService.AddDict(dict);

            return(this.Json(me, JsonRequestBehavior.DenyGet));
        }
Exemplo n.º 25
0
        private void HandleEntityNetworkMessage(MsgEntity message)
        {
            if (message.SourceTick <= _gameStateManager.CurServerTick)
            {
                DispatchMsgEntity(message);
                return;
            }

            _queue.Add(message);
        }
        public NetworkComponentMessage(MsgEntity netMsg, ICommonSession?session = null)
        {
            DebugTools.Assert(netMsg.Type == EntityMessageType.ComponentMessage);

            Channel   = netMsg.MsgChannel;
            EntityUid = netMsg.EntityUid;
            NetId     = netMsg.NetId;
            Message   = netMsg.ComponentMessage;
            Session   = session;
        }
Exemplo n.º 27
0
        private void chatControl1_BeginToSend(string content)
        {
            this.chatControl1.ShowMessage(Common.UserName, DateTime.Now, content, true);

            imageDict = this.chatControl1.imageDict;

            //把控件中的图片字典,添加到图片包装类列表中
            foreach (KeyValuePair <string, Image> kv in imageDict)
            {
                ImageWrapper newWrapper = new ImageWrapper(kv.Key, kv.Value);

                imageWrapperList.Add(newWrapper);
            }

            //清除控件中图片字典的内容
            this.chatControl1.ClearImageDic();

            //从客户端 Common中获取相应连接
            Connection p2pConnection = Common.GetUserConn(this.friendID);

            if (p2pConnection != null)
            {
                MsgEntity chatContract = new MsgEntity();
                chatContract.SenderID = Common.UserID;

                chatContract.Reciver = this.friendID;

                chatContract.MsgContent = content;
                chatContract.SendTime   = DateTime.Now;
                //chatContract.ImageList = imageWrapperList;
                p2pConnection.SendObject("ClientChatMessage", chatContract);
                this.chatControl1.Focus();

                imageWrapperList.Clear();

                LogInfo.LogMessage("通过p2p通道发送消息,当前用户ID为" + Common.UserID + "当前Tcp连接端口号" + p2pConnection.ConnectionInfo.LocalEndPoint.Port.ToString(), "P2PINFO");
            }
            else
            {
                MsgEntity chatContract = new MsgEntity();
                chatContract.SenderID = Common.UserID;

                chatContract.Reciver = this.friendID;

                chatContract.MsgContent = content;
                chatContract.SendTime   = DateTime.Now;
                //chatContract.ImageList = imageWrapperList;
                Common.TcpConn.SendObject("ChatMessage", chatContract);
                this.chatControl1.Focus();
                imageWrapperList.Clear();

                LogInfo.LogMessage("服务器转发消息", "P2PINFO");
            }
        }
 /// <summary>
 /// 接受并分析消息
 /// </summary>
 /// <param name="Me">重新封装组合的消息列表</param>
 public static void OnReceivedMsgAnalyseMsgCompleted(MsgEntity Me)
 {
     if (ReceivedMsgAnalyseMsgCompleted != null)
     {
         ReceivedMsgAnalyseMsgCompleted.Invoke(Me);
     }
     else
     {
         throw new Exception("未实现方法CommonMethodCallBackHandlers.ReceivedMsgAnalyseMsgCompleted");
     }
 }
Exemplo n.º 29
0
        public MsgEntity AccountLogout()
        {
            MsgEntity r = ResponseMsg.SetEntity(out r, 4201);

            if (HttpContext.Current.Session[sessionName] != null)
            {
                HttpContext.Current.Session.Abandon();
            }

            return(r);
        }
Exemplo n.º 30
0
 /// <summary>
 /// 发送消息
 /// </summary>
 public void SendMsg(string channel, MsgEntity msg, bool isSave = false)
 {
     Task.Factory.StartNew(() =>
     {
         _redisHelper.Publish(channel, msg.JsonSerialize());
         // 保存消息
         if (isSave)
         {
             SaveMsg(channel, msg);
         }
     });
 }