1.客户端A发送聊天消息给服务器
button_send_Click(object sender, EventArgs e) 7 { 8 string chatText = this.richTextBox_Write.Text; 9 if (string.IsNullOrEmpty(chatText)) 10 { ); 12 return; 13 } 14 ChatMsg chatMsg = new ChatMsg(this.selfUserID, this.friendID, chatText); 15 this.tcpPassiveEngine.SendMessageToServer(chatMsg.ToContractStream()); 16 this.ShowChatMsg(chatMsg); 17 }
View Code2.服务端转发聊天消息
1 if (msgType == MsgType.Chatting) 2 { 3 ChatMsg chatMsg = MsgHelper.DeserializeMsg<ChatMsg>(msg); 4 if (this.onlineManager.GetKeyList().Contains(chatMsg.TargetUserID)) 5 { 6 IPEndPoint targetUserAddress = this.onlineManager.Get(chatMsg.TargetUserID).Address; 7 this.tcpServerEngine.SendMessageToClient(targetUserAddress, msg); 8 } 9 }
View Code3.客户端B接收并显示聊天消息
1 void tcpPassiveEngine_MessageReceived(IPEndPoint userAddress, byte[] msg) 2 { msgType = BitConverter.ToInt32(msg, 0); (msgType == MsgType.Chatting) 7 { 8 ChatMsg chatMsg = MsgHelper.DeserializeMsg<ChatMsg>(msg); 9 this.ShowChatForm(chatMsg.SourceUserID); 10 this.ChatMsgReceived(chatMsg); 11 } 12 } 显示聊天窗 ShowChatForm(string friendUserID) 19 { 20 if (this.InvokeRequired) 21 { 22 this.Invoke(new CbGeneric<string>(this.ShowChatForm), friendUserID); 23 } { 26 ChatForm form = this.chatFormManager.GetForm(friendUserID); 27 if (form == null) 28 { 29 form = new ChatForm(this.selfID, friendUserID, this, this.tcpPassiveEngine); , friendUserID); 31 this.chatFormManager.Add(form); 32 form.Show(); 33 } 34 form.Focus(); 35 } 36 } 显示聊天消息 ShowChatMsg(ChatMsg chatMsg) 44 { 45 if (this.InvokeRequired) 46 { 47 this.Invoke(new CbGeneric<ChatMsg>(this.formMain_chatMsgReceived), chatMsg); 48 } { + chatMsg.TimeSent.ToString() + ); ); 53 this.richTextBox_Write.Clear(); 54 } 55 }
View Code