예제 #1
0
        /// <summary>
        /// 动态隐藏方法
        /// </summary>
        /// <param name="hideTo">隐藏后的动作</param>
        private void HideMe(HideTo hideTo)
        {
            UnityModule.DebugPrint("开始动态隐藏窗体...{0}", this.Name);
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate {
                int IniTop = this.Top;
                while (this.Opacity > 0)
                {
                    this.Opacity -= 0.1;
                    this.Top     -= 2;
                    Thread.Sleep(15);
                }

                if (hideTo == HideTo.Min)
                {
                    UnityModule.DebugPrint("最小化窗体");
                    this.WindowState = FormWindowState.Minimized;
                    this.Opacity     = 1.0;
                    this.Top         = IniTop;
                }
                else if (hideTo == HideTo.JusetClose)
                {
                    UnityModule.DebugPrint("关闭ClientForm");
                    //初始化FriendItem静态数据,否则再次登录后会出现问题
                    FriendItem.ResetStaticData();
                    AllowToClose = true;
                    this.Close();
                }
                else if (hideTo == HideTo.ExitApp)
                {
                    UnityModule.DebugPrint("退出程序");
                    AllowToClose = true;
                    ExitApplication();
                }
            }));
        }
예제 #2
0
        /// <summary>
        /// FriendItem激活项改变,切换聊天记录控件
        /// </summary>
        /// <param name="OldActiveItem"></param>
        /// <param name="NewActiveItem"></param>
        private void FriendItemActiveChanged(object OldActiveItem, FriendItem NewActiveItem)
        {
            if ((FriendItem)OldActiveItem != null)
            {
                UnityModule.DebugPrint("旧的激活项:{0}", ((FriendItem)OldActiveItem).FriendID);
                ((FriendItem)OldActiveItem).ChatDraft = ChatInputTextBox.Text;
                ((FriendItem)OldActiveItem).ChatBubblesPanel?.Hide();
            }
            if ((FriendItem)NewActiveItem != null)
            {
                UnityModule.DebugPrint("新的激活项:{0}", ((FriendItem)NewActiveItem).FriendID);
                if (!ChatSendPanel.Visible)
                {
                    ChatSendPanel.Show();
                }

                ChatInputTextBox.Text = NewActiveItem.ChatDraft;
                if (NewActiveItem.ChatBubblesPanel != null)
                {
                    NewActiveItem.ChatBubblesPanel.Show();
                    NewActiveItem.ChatBubblesPanel.BringToFront();
                }
            }
            else
            {
                ChatSendPanel.Hide();
            }
        }
예제 #3
0
        private void LoginForm_Load(object sender, EventArgs e)
        {
            //设置标题图标
            TitleLabel.Image = UnityResource.Speleon.ToBitmap();
            //设置控件的容器关系
            TitleLabel.Parent     = ActiveBGIBOX;
            MinButton.Parent      = ActiveBGIBOX;
            CloseButton.Parent    = ActiveBGIBOX;
            LoginAreaLabel.Parent = ActiveBGIBOX;
            TipsPanel.Parent      = ActiveBGIBOX;

            //绑定鼠标拖动事件
            this.MouseDown           += new MouseEventHandler(UnityModule.MoveFormViaMouse);
            ActiveBGIBOX.MouseDown   += new MouseEventHandler(UnityModule.MoveFormViaMouse);
            TitleLabel.MouseDown     += new MouseEventHandler(UnityModule.MoveFormViaMouse);
            LoginAreaLabel.MouseDown += new MouseEventHandler(UnityModule.MoveFormViaMouse);

            //防止输入框选中
            UserIDTextBox.SelectionStart    = UserIDTextBox.Text.Length;
            UserIDTextBox.SelectionLength   = 0;
            PasswordTextBox.SelectionStart  = PasswordTextBox.Text.Length;
            PasswordTextBox.SelectionLength = 0;

            //记录关闭Tips事件句柄
            CloseTipsEventHandler = new EventHandler(TipsClsoeButton_Click);

            UnityModule.DebugPrint("窗体加载成功");
        }
예제 #4
0
        /// <summary>
        /// 动态隐藏方法
        /// </summary>
        /// <param name="hideTo">隐藏后的动作</param>
        private void HideMe(HideTo hideTo)
        {
            UnityModule.DebugPrint("开始动态隐藏窗体...{0}", this.Name);
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate {
                int IniTop = this.Top;
                while (this.Opacity > 0)
                {
                    this.Opacity -= 0.1;
                    this.Top     -= 2;
                    Thread.Sleep(15);
                }

                if (hideTo == HideTo.Min)
                {
                    UnityModule.DebugPrint("最小化窗体");
                    this.WindowState = FormWindowState.Minimized;
                    this.Opacity     = 1.0;
                    this.Top         = IniTop;
                }
                else if (hideTo == HideTo.JustHide)
                {
                    this.Hide();
                    this.Opacity      = 1.0;
                    this.Top          = IniTop;
                    SignInButton.Text = "Sign In";
                }
                else if (hideTo == HideTo.Close)
                {
                    UnityModule.DebugPrint("退出程序");
                    AllowToClose = true;
                    Application.Exit();
                }
            }));
        }
예제 #5
0
        private void ClientForm_Shown(object sender, EventArgs e)
        {
            this.Invalidate();
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate {
                try
                {
                    UnitySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    UnitySocket.Connect(UnityModule.ServerIP, UnityModule.ServerPort);
                    ReceiveThread = new Thread(ReceiveMessage);
                    ReceiveThread.Start();

                    //发送WHOAMI数据,告诉服务端自己的USERID
                    UnitySocket.Send(Encoding.UTF8.GetBytes(ProtocolFormatter.FormatProtocol(ProtocolFormatter.CMDType.WhoAmI, Application.ProductVersion, UnityModule.USERID)));
                    UnityModule.DebugPrint("WHOAMI 数据包发送成功!");

                    //发送获取好友列表请求
                    UnitySocket.Send(Encoding.UTF8.GetBytes(ProtocolFormatter.FormatProtocol(ProtocolFormatter.CMDType.GetFriendsList, Application.ProductVersion, UnityModule.USERID)));
                    UnityModule.DebugPrint("GETFRIENDSLIST 数据包发送成功!");
                }
                catch (Exception ex)
                {
                    this.Invoke(new Action(() => {
                        new MyMessageBox("连接服务器遇到错误:{0}", ex.Message).ShowDialog(this);
                    }));
                }
            }));
        }
예제 #6
0
 private void CloseButton_Click(object sender, EventArgs e)
 {
     UnityModule.DebugPrint("点击关闭按钮");
     CloseButton.Image = UnityResource.Close_1;
     CloseButton.Invalidate();
     TryToClose();
     CloseButton.Image = UnityResource.Close_0;
     CloseButton.Invalidate();
 }
예제 #7
0
        public ClientForm()
        {
            //禁用多线程UI检查
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            //设置 图标 和 绘制方式(减少闪烁)
            this.Icon = UnityResource.Speleon;
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            UpdateStyles();

            //为窗体增加阴影
            UnityModule.DrawWindowShadow(this);
            UnityModule.DebugPrint("ClientForm 窗体创建成功");
        }
예제 #8
0
        /// <summary>
        /// 获取指定协议类型的正则表达式
        /// </summary>
        /// <param name="cmdType">协议类型</param>
        /// <returns>指定协议的正则表达式</returns>
        static public string GetProtocolPattern(CMDType cmdType)
        {
            UnityModule.DebugPrint("开始获取协议正则表达式:{0}", cmdType.ToString());
            string ProtocolString = null;

            //每条协议最后使用换行符结束
            switch (cmdType)
            {
            case CMDType.ChatMessage:
            {
                ProtocolString = "HI_CMDTYPE=CHATMESSAGE_FROMID=(?<FROMID>.+?)_CHATTIME=(?<CHATTIME>.+?)_MESSAGEID=(?<MESSAGEID>.+?)_MESSAGE=(?<MESSAGE>.+?)\n";
                break;
            }

            case CMDType.GetFriendsList:
            {
                ProtocolString = "HI_CMDTYPE=GETFRIENDSLIST_FRIENDID=(?<FRIENDID>.+?)_NICKNAME=(?<NICKNAME>.+?)_SIGNATURE=(?<SIGNATURE>.+?)_ONLINE=(?<ONLINE>.+?)\n";
                break;
            }

            case CMDType.FriendSignIn:
            {
                ProtocolString = "HI_CMDTYPE=FRIENDSIGNIN_FRIENDID=(?<FRIENDID>.+?)\n";
                break;
            }

            case CMDType.FriendSignOut:
            {
                ProtocolString = "HI_CMDTYPE=FRIENDSIGNOUT_FRIENDID=(?<FRIENDID>.+?)\n";
                break;
            }

            default:
            {
                ProtocolString = "";
                break;
            }
            }
            UnityModule.DebugPrint("协议正则表达式:{0}", ProtocolString);
            return(ProtocolString);
        }
예제 #9
0
        /// <summary>
        /// 弹出提示窗口
        /// </summary>
        /// <param name="MessageText">消息文本</param>
        /// <param name="Title">消息标题</param>
        /// <param name="iconType">图表类型</param>
        public MyMessageBox(string MessageText, string Title, IconType iconType = IconType.Info)
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

            TitleLabel.Text   = Title;
            this.Text         = Title;
            MessageLabel.Text = MessageText;
            IconLabel.Image   = UnityResource.ResourceManager.GetObject(iconType.ToString()) as Image;
            if (iconType == IconType.Question)
            {
                CancelButton.Left = (this.Width - CancelButton.Width * 2 - 20) / 2;
                OKButton.Left     = CancelButton.Right + 20;
            }
            else
            {
                CancelButton.Hide();
                OKButton.Left = (this.Width - OKButton.Width) / 2;
            }

            //为窗体增加阴影
            UnityModule.DrawWindowShadow(this);
        }
예제 #10
0
        private void ClientForm_Load(object sender, EventArgs e)
        {
            //设置标题图标
            TitleLabel.Image = UnityResource.Speleon.ToBitmap();

            //绑定鼠标拖动事件
            this.MouseDown       += new MouseEventHandler(UnityModule.MoveFormViaMouse);
            TitleLabel.MouseDown += new MouseEventHandler(UnityModule.MoveFormViaMouse);
            TitlePanel.MouseDown += new MouseEventHandler(UnityModule.MoveFormViaMouse);

            //为关闭按钮设置动态效果
            CloseButton.MouseEnter += new EventHandler(delegate(object s, EventArgs ea) { CloseButton.Image = UnityResource.Close_1 as Image; });
            CloseButton.MouseLeave += new EventHandler(delegate(object s, EventArgs ea) { CloseButton.Image = UnityResource.Close_0 as Image; });
            CloseButton.MouseDown  += new MouseEventHandler(delegate(object s, MouseEventArgs mea) { CloseButton.Image = UnityResource.Close_2; });

            //为 FriendItem 赋值 ParentPanel 属性,并绑定事件
            FriendItem.ParentPanel        = FriendsFlowPanel;
            FriendItem.ActiveItemChanged += new EventHandler <FriendItem>(FriendItemActiveChanged);

            BubbleMaxWidth = MainPanel.Width - 60;

            UnityModule.DebugPrint("窗体加载成功");
        }
예제 #11
0
 private void CloseButton_Click(object sender, EventArgs e)
 {
     UnityModule.DebugPrint("点击关闭按钮");
     HideMe(HideTo.Close);
 }
예제 #12
0
 private void MaxButton_Click(object sender, EventArgs e)
 {
     UnityModule.DebugPrint("点击最大化按钮");
     this.WindowState = FormWindowState.Maximized;
 }
예제 #13
0
 private void MinButton_Click(object sender, EventArgs e)
 {
     UnityModule.DebugPrint("点击最小化按钮");
     HideMe(HideTo.Min);
 }
예제 #14
0
 private void RestoreButton_Click(object sender, EventArgs e)
 {
     UnityModule.DebugPrint("点击还原按钮");
     this.WindowState = FormWindowState.Normal;
 }
예제 #15
0
        /// <summary>
        /// 登录
        /// </summary>
        private void Login()
        {
            //更新界面
            this.Invoke(new Action(() => {
                UserIDTextBox.Enabled   = false;
                PasswordTextBox.Enabled = false;
                SignInButton.Text       = "Cancel";
                this.Invalidate();
            }));

            try
            {
                //创建TCP连接
                LoginSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                LoginSocket.Connect(UnityModule.ServerIP, UnityModule.ServerPort);
                //发送登录协议
                LoginSocket.Send(Encoding.ASCII.GetBytes(ProtocolFormatter.FormatProtocol(ProtocolFormatter.CMDType.SignIn, Application.ProductVersion, UserIDTextBox.Text, PasswordTextBox.Text)));
                //接收登录验证结果
                byte[] SignResultBytes = new byte[LoginSocket.ReceiveBufferSize - 1];
                LoginSocket.Receive(SignResultBytes);
                string SignResult = Encoding.ASCII.GetString(SignResultBytes).Trim('\0');
                UnityModule.DebugPrint("接收到登录结果:{0}", SignResult);

                string MessagePattern     = ProtocolFormatter.GetCMDTypePattern();
                Regex  MessageRegex       = new Regex(MessagePattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                Match  MessageMatchResult = MessageRegex.Match(SignResult);
                string cmdType            = MessageMatchResult.Groups["CMDTYPE"].Value.ToUpper();
                switch (cmdType)
                {
                case "SIGNINSUCCESSFULLY":
                {
                    //登录成功,切换界面
                    this.Invoke(new Action(() =>
                        {
                            ShowTips("登录成功!");
                            SignInButton.Text = "Success.";
                            this.Invalidate();
                            UnityModule.USERID = UserIDTextBox.Text;
                            new ClientForm()
                            {
                                loginForm = this
                            }.Show();
                            HideMe(HideTo.JustHide);
                        }));
                    break;
                }

                case "SIGNINUNSUCCESSFULLY":
                {
                    //登录失败
                    this.Invoke(new Action(() =>
                        {
                            ShowTips("您的密码输入错误,请重试!");
                            SignInButton.Text = "Sign In";
                            PasswordTextBox.Focus();
                        }));
                    break;
                }
                }

                LoginSocket?.Close();
                UnityModule.DebugPrint("验证登录TCP连接已经关闭 ...");

                UserIDTextBox.Enabled   = true;
                PasswordTextBox.Enabled = true;
                this.Invalidate();
            }
            catch (ThreadAbortException)
            {
                //遇到线程中断异常时忽略,因为此异常由用户手动取消放弃登录任务。
                return;
            }
            catch (Exception ex)
            {
                //登录过程中遇到错误
                Logining = false;
                UnityModule.DebugPrint("登录遇到错误!{0}", ex.Message);
                this.Invoke(new Action(() =>
                {
                    UserIDTextBox.Enabled   = true;
                    PasswordTextBox.Enabled = true;
                    SignInButton.Text       = "Sign In";
                    this.Invalidate();
                    ShowTips("登录遇到错误,请检查网络连接。" + Convert.ToString(ex.HResult, 16));
                }));
            }

            Logining = false;
        }
예제 #16
0
        /// <summary>
        /// 接收来自服务器的消息
        /// </summary>
        private void ReceiveMessage()
        {
            while (true)
            {
                #region 接收消息
                byte[] MessageBuffer        = new byte[] { };
                int    MessageBufferSize    = 0;
                string ServerMessagePackage = "";

                try
                {
                    MessageBuffer        = new byte[UnitySocket.ReceiveBufferSize - 1];
                    MessageBufferSize    = UnitySocket.Receive(MessageBuffer);
                    ServerMessagePackage = Encoding.UTF8.GetString(MessageBuffer, 0, MessageBufferSize);
                }
                catch (ThreadAbortException) { return; }
                catch (Exception ex)
                {
                    UnityModule.DebugPrint("接收消息时遇到错误:{0}", ex.Message);
                    HideMe(HideTo.JusetClose);
                    this.loginForm.Show();
                    this.loginForm.ShowTips("与服务器连接中断,请检查网络连接。" + Convert.ToString(ex.HResult, 16));
                    return;
                }

                UnityModule.DebugPrint("ServerMessagePackage : {0}", ServerMessagePackage);
                #endregion

                /*
                 * 遇到严重的TCP粘包问题,服务端分多次发送的GETFRIENDSLIST协议,被一次发送给了客户端
                 * 导致客户端只能提取到第一条协议,因为每条协议以'\n'结尾,所以每次收到数据包后对其按'\n'分割
                 * 分割后判断不为空的段后加'\n'再按正常的协议包处理,为空不处理
                 * 以上,解决粘包问题
                 */
                string[] ServerMessages = ServerMessagePackage.Split('\n');
                foreach (string TempServerMessage in ServerMessages)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(TempServerMessage))
                        {
                            continue;
                        }

                        #region 读取消息协议类型
                        string ServerMessage = TempServerMessage + '\n';
                        UnityModule.DebugPrint("ServerMessage : {0}", ServerMessage);
                        string MessagePattern     = ProtocolFormatter.GetCMDTypePattern();
                        Regex  MessageRegex       = new Regex(MessagePattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                        Match  MessageMatchResult = MessageRegex.Match(ServerMessage);
                        string cmdType            = MessageMatchResult.Groups["CMDTYPE"].Value.ToUpper();
                        UnityModule.DebugPrint("收到 CMDTYPE : {0}", cmdType);
                        #endregion

                        switch (cmdType)
                        {
                        case "CHATMESSAGE":
                        {
                            #region 聊天消息
                            string   FromID = null, Message = null;
                            int      MessageID;
                            DateTime ChatTime;
                            MessagePattern     = ProtocolFormatter.GetProtocolPattern(ProtocolFormatter.CMDType.ChatMessage);
                            MessageRegex       = new Regex(MessagePattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                            MessageMatchResult = MessageRegex.Match(ServerMessage);
                            FromID             = MessageMatchResult.Groups["FROMID"].Value;
                            ChatTime           = DateTime.TryParse(MessageMatchResult.Groups["CHATTIME"].Value.ToString(), out ChatTime) ? ChatTime.ToLocalTime() : DateTime.Now;
                            MessageID          = int.Parse(MessageMatchResult.Groups["MESSAGEID"].Value);
                            Message            = Encoding.UTF8.GetString(Convert.FromBase64String(MessageMatchResult.Groups["MESSAGE"].Value));

                            this.Invoke(new Action(() =>
                                {
                                    FriendItem MessageFrom = FriendItem.GetFriendItemByFriendID(FromID);
                                    if (MessageFrom != null)
                                    {
                                        FriendsFlowPanel.Controls.SetChildIndex(MessageFrom, 0);

                                        if (FriendItem.ActiveFriend != MessageFrom)
                                        {
                                            MessageFrom.MessageNRTCount += 1;
                                        }

                                        MessageFrom.ChatBubblesPanel.Controls.Add(
                                            new ChatBubble
                                            (
                                                MessageID.ToString(),
                                                ChatTime.ToString(),
                                                FromID,
                                                Message,
                                                BubbleMaxWidth,
                                                false
                                            )
                                            );
                                    }
                                }));
                            break;
                            #endregion
                        }

                        case "GETCHATHISTORY":
                        {
                            #region 获取历史聊天记录
                            //todo:显示历史聊天记录
                            string FromID    = "";
                            int    MessageID = 0;
                            //更新本地第一条聊天记录MessageID
                            if (FriendsFirstMessageID.ContainsKey(FromID))
                            {
                                //如果遇到更小的MessageID,只有
                                if (MessageID < FriendsFirstMessageID[FromID])
                                {
                                    FriendsFirstMessageID[FromID] = MessageID;
                                }
                            }
                            else
                            {
                                //估计运行不到这里
                                FriendsFirstMessageID.Add(FromID, MessageID);
                            }
                            break;
                            #endregion
                        }

                        case "GETFRIENDSLIST":
                        {
                            #region 获取好友列表
                            string FriendID = null, NickName = null, Signature = null; bool OnLine = false;
                            MessagePattern     = ProtocolFormatter.GetProtocolPattern(ProtocolFormatter.CMDType.GetFriendsList);
                            MessageRegex       = new Regex(MessagePattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                            MessageMatchResult = MessageRegex.Match(ServerMessage);
                            FriendID           = MessageMatchResult.Groups["FRIENDID"].Value.ToString();
                            NickName           = Encoding.UTF8.GetString(Convert.FromBase64String(MessageMatchResult.Groups["NICKNAME"].Value.ToString()));
                            Signature          = Encoding.UTF8.GetString(Convert.FromBase64String(MessageMatchResult.Groups["SIGNATURE"].Value.ToString()));
                            OnLine             = Convert.ToBoolean(MessageMatchResult.Groups["ONLINE"].Value.ToString());

                            this.Invoke(new Action(() =>
                                {
                                    UnityModule.DebugPrint("收到好友信息:{1} ({0}):{2}", FriendID, NickName, Signature);

                                    if (FriendItem.FriendExisted(FriendID))
                                    {
                                        //TODO:如果 FriendID已经存在,且FriendItem不为null,仅更新FriendID的信息,此特性可以在服务端用于有用户更新了资料时,立即向好友客户端更新资料
                                        FriendItem.GetFriendItemByFriendID(FriendID)?.SetNickNameSignatureAndOnLine(NickName, Signature, OnLine);
                                    }
                                    else
                                    {
                                        //默认好友聊天历史记录最早一条MessageID=0
                                        if (!FriendsFirstMessageID.ContainsKey(FriendID))
                                        {
                                            FriendsFirstMessageID.Add(FriendID, 0);
                                        }
                                        //新添加 FriendItem
                                        FriendItem NewFriendItem = new FriendItem(FriendID, NickName, Signature, OnLine)
                                        {
                                            RightToLeft = RightToLeft.No
                                        };
                                        NewFriendItem.FriendItemClick += new EventHandler(FriendItemClick);

                                        //创建好友聊天记录控件
                                        MyTableLayoutPanel NewChatBubblePanel = new MyTableLayoutPanel()
                                        {
                                            AutoScroll = true,
                                            Dock       = DockStyle.Fill,
                                            BackColor  = Color.White,
                                            Visible    = false,
                                        };

                                        //绑定自动滚动到底部事件
                                        NewChatBubblePanel.ControlAdded += new ControlEventHandler(ChatBubblesPanel_ControlAdded);

                                        MainPanel.Controls.Add(NewChatBubblePanel);

                                        NewFriendItem.ChatBubblesPanel = NewChatBubblePanel;
                                        FriendsFlowPanel.Controls.Add(NewFriendItem);
                                    }
                                }));
                            break;
                            #endregion
                        }

                        case "FRIENDSIGNIN":
                        {
                            #region 好友登录
                            string FriendID = null;
                            MessagePattern     = ProtocolFormatter.GetProtocolPattern(ProtocolFormatter.CMDType.FriendSignIn);
                            MessageRegex       = new Regex(MessagePattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                            MessageMatchResult = MessageRegex.Match(ServerMessage);
                            FriendID           = MessageMatchResult.Groups["FRIENDID"].Value.ToString();

                            this.Invoke(new Action(() =>
                                {
                                    UnityModule.DebugPrint("收到好友登录消息:{0}", FriendID);
                                    if (FriendItem.FriendExisted(FriendID))
                                    {
                                        FriendItem JustSignIn = FriendItem.GetFriendItemByFriendID(FriendID);
                                        if (JustSignIn != null)
                                        {
                                            FriendsFlowPanel.Controls.SetChildIndex(JustSignIn, FriendItem.OnLineCount);
                                            JustSignIn.OnLine = true;
                                        }
                                    }
                                }));

                            break;
                            #endregion
                        }

                        case "FRIENDSIGNOUT":
                        {
                            #region 好友注销登录
                            string FriendID = null;
                            MessagePattern     = ProtocolFormatter.GetProtocolPattern(ProtocolFormatter.CMDType.FriendSignOut);
                            MessageRegex       = new Regex(MessagePattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                            MessageMatchResult = MessageRegex.Match(ServerMessage);
                            FriendID           = MessageMatchResult.Groups["FRIENDID"].Value.ToString();

                            this.Invoke(new Action(() =>
                                {
                                    UnityModule.DebugPrint("收到好友注销消息:{0}", FriendID);
                                    if (FriendItem.FriendExisted(FriendID))
                                    {
                                        FriendItem JustSignIn = FriendItem.GetFriendItemByFriendID(FriendID);
                                        if (JustSignIn != null)
                                        {
                                            JustSignIn.OnLine = false;
                                            FriendsFlowPanel.Controls.SetChildIndex(JustSignIn, FriendItem.OnLineCount);
                                        }
                                    }
                                }));
                            break;
                            #endregion
                        }

                        case "FRIENDSLISTCOMPLETE":
                        {
                            #region 好友列表获取完毕
                            UnitySocket.Send(Encoding.UTF8.GetBytes(ProtocolFormatter.FormatProtocol(ProtocolFormatter.CMDType.GetMessageNotSendYet, Application.ProductVersion, UnityModule.USERID)));
                            break;
                            #endregion
                        }

                        case "MESSAGENSYCOMPLETE":
                        {
                            #region 未读消息获取完毕
                            //准备完毕,测试用
                            UnitySocket.Send(Encoding.UTF8.GetBytes(ProtocolFormatter.FormatProtocol(ProtocolFormatter.CMDType.GetChatHistory, Application.ProductVersion, "66666", "0")));
                            break;
                            #endregion
                        }

                        case "ANOTHORSIGNIN":
                        {
                            #region 异地登录
                            this.Invoke(new Action(() =>
                                {
                                    HideMe(HideTo.JusetClose);
                                    this.loginForm.Show();
                                    this.loginForm.ShowTips("您的账号异地登陆,请注意密码安全!");
                                    UnitySocket.Close();
                                    ReceiveThread.Abort();
                                }));
                            //这里需要 return; 否则会进入 catch(){} 被当做异常处理
                            return;

                            #endregion
                        }

                        case "SERVERSHUTDOWN":
                        {
                            #region 远程服务端关闭
                            this.Invoke(new Action(() => {
                                    HideMe(HideTo.JusetClose);
                                    this.loginForm.Show();
                                    this.loginForm.ShowTips("远程服务器主动关闭,可能Leon关机去上课了...");
                                    UnitySocket.Close();
                                    ReceiveThread.Abort();
                                }));
                            return;

                            #endregion
                        }

                        default:
                        {
                            #region 未知的消息协议
                            this.Invoke(new Action(() =>
                                {
                                    new MyMessageBox("遇到未知的 CMDTYPE : " + cmdType, MyMessageBox.IconType.Info).Show(this);
                                }));
                            break;
                            #endregion
                        }
                        }
                    }
                    catch (ThreadAbortException) { return; }
                    catch (Exception ex)
                    {
                        UnityModule.DebugPrint("处理消息时遇到错误:{0}", ex.Message);
                    }
                }
            }
        }
예제 #17
0
        /// <summary>
        /// 获取按指定协议类型格式化的协议字符串
        /// </summary>
        /// <param name="cmdType">协议类型</param>
        /// <returns>协议字符串</returns>
        static public string FormatProtocol(CMDType cmdType, params string[] ProtocolValues)
        {
            UnityModule.DebugPrint("开始格式化通信协议:{0} : {1}", cmdType.ToString(), string.Join(" + ", ProtocolValues));
            //每条协议最后加一个换行符,否则服务端无法使用正则匹配最后一个参数
            string ProtocolString = "";

            try
            {
                switch (cmdType)
                {
                case CMDType.ChatMessage:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=CHATMESSAGE_TOID={1}_MESSAGE={2}\n", ProtocolValues[0], ProtocolValues[1], Convert.ToBase64String(Encoding.UTF8.GetBytes(ProtocolValues[2])));
                    break;
                }

                case CMDType.SignIn:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=SIGNIN_USERID={1}_PASSWORD={2}\n", ProtocolValues[0], ProtocolValues[1], ProtocolValues[2]);
                    break;
                }

                case CMDType.WhoAmI:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=WHOAMI_USERID={1}\n", ProtocolValues[0], ProtocolValues[1]);
                    break;
                }

                case CMDType.GetFriendsList:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=GETFRIENDSLIST_USERID={1}\n", ProtocolValues[0], ProtocolValues[1]);
                    break;
                }

                case CMDType.SignOut:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=SIGNOUT_USERID={1}\n", ProtocolValues[0], ProtocolValues[1]);
                    break;
                }

                case CMDType.GetMessageNotSendYet:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=GETMESSAGENOTSENDYET_USERID={1}\n", ProtocolValues[0], ProtocolValues[1]);
                    break;
                }

                case CMDType.GetChatHistory:
                {
                    ProtocolString = string.Format("HEY_CVER={0}_CMDTYPE=GETCHATHISTORY_FRIENDID={1}_FIRSTMESSAGEID={2}\n", ProtocolValues[0], ProtocolValues[1], ProtocolValues[2]);
                    break;
                }

                default:
                {
                    ProtocolString = "";
                    break;
                }
                }
                UnityModule.DebugPrint("协议内容:{0}", ProtocolString);
                return(ProtocolString);
            }
            catch (Exception ex)
            {
                UnityModule.DebugPrint("获取 {0} 通信协议时遇到错误:{1}", cmdType.ToString(), ex.Message);
                return("");
            }
        }