Beispiel #1
0
        /// <summary>
        /// 处理服务器信息
        /// </summary>
        private void ReceiveData()
        {
            string receiveString  = null;
            Action actionDelegate = null;

            while (_isExit == false)
            {
                try
                {
                    //从网络流中读出字符串
                    //此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串
                    receiveString = StartReadFile();
                    if (string.IsNullOrEmpty(receiveString))
                    {
                        continue;
                    }
                }
                catch
                {
                    if (_isExit == false)
                    {
                        MessageBox.Show("与服务器失去连接");
                    }
                    break;
                }
                string[] splitString = receiveString.Split(',');
                string   command     = splitString[0].ToLower();
                actionDelegate = null;
                if (_nickName == splitString[1])
                {
                    continue;
                }
                switch (command)
                {
                case "login":       //格式: login,用户名
                    actionDelegate = () =>
                    {
                        FormChat form = new FormChat(_nickName, splitString[1]);
                        form.OnSendMessage += form_OnSendMessage;
                        _lstChatForm.Add(splitString[1], form);
                        lstFriend.Items.Add(splitString[1]);
                    };

                    break;

                case "logout":      //格式: logout,用户名
                    actionDelegate = () =>
                    {
                        FormChat form = _lstChatForm[splitString[1]];
                        form.ShowTips("对方已经离线,可能无法立即回复");
                        _lstChatForm.Remove(splitString[1]);
                        lstFriend.Items.Remove(splitString[1]);
                    };
                    break;

                case "talk":        //格式: talk,用户名,对话信息
                    actionDelegate = () =>
                    {
                        FormChat form = _lstChatForm[splitString[1]];
                        form.Show();
                        form.AppendRtf(splitString[2], splitString[1]);
                    };
                    break;

                default:
                    break;
                }
                if (actionDelegate != null)
                {
                    this.Invoke(actionDelegate);
                }
            }
            Application.Exit();
        }