Tcp-based chat program breeze IM (c # Open Source ),
Currently, breeze IM sends messages in the form of server forwarding.
When a user chats, the message is first sent to the server and then forwarded to the target user:
The client sends a message:
ChatContract chatContract = new ChatContract(); chatContract.UserID = Common.UserID; chatContract.UserName = Common.UserName; chatContract.DestUserID = this.friendID; chatContract.DestUserName = this.friendID; chatContract.Content = content; chatContract.SendTime = DateTime.Now; Common.TcpConn.SendObject<ChatContract>("ChatMessage", chatContract);
/// <Summary> // This contract class stores chat conversation messages // </summary> [ProtoContract] public class ChatContract {// user ID [ProtoMember (1)] public string UserID {get; set;} // user name [ProtoMember (2)] public string UserName {get; set ;}// target user ID [ProtoMember (3)] public string DestUserID {get; set;} // target username [ProtoMember (4)] public string DestUserName {get; set;} // chat content, mainly text message [ProtoMember (5)] public string Content {get; set ;}// sending time [ProtoMember (6)] public DateTime SendTime {get; set ;} public ChatContract () {} public ChatContract (string userID, string userName, string destUserID, string destUserName, string content, DateTime sendTime) {this. userID = userID; this. userName = userName; this. destUserID = destUserID; this. destUserName = destUserName; this. content = content; this. sendTime = sendTime ;}}ChatContract contract
Server:
Registering Message Processing Methods
// NetworkComms. AppendGlobalIncomingPacketHandler <ChatContract> ("ChatMessage", IncomingChatMessage) for client-side chat information forwarding );
Solution
Private void IncomingChatMessage (PacketHeader header, Connection connection, ChatContract chatContract) {try {lock (syncLocker) {// if the user is online, the target user in the User Manager determines whether the target user is online if (userManager. containsKey (chatContract. destUserID) {// userManager [chatContract. destUserID]. sendObject ("ServerChatMessage", chatContract); // there should be only one returned Connection. However, because the returned Connection is a list, you can traverse it by using foreach (Connection conn in NetworkComms. getExistingConnection (userManager [chatContract. destUserID], ConnectionType. TCP) {conn. sendObject ("ServerChatMessage", chatContract) ;}// if the user is not online, add the data to the database else {OffLineMessage msg = new OffLineMessage (); msg. userID = chatContract. userID; msg. userName = chatContract. userName; msg. destUserID = chatContract. destUserID; msg. destUerName = chatContract. destUserName; msg. chatContent = chatContract. content; msg. sendTime = chatContract. sendTime; DoOffLineMessage. save (msg) ;}} catch (Exception ex) {LogTools. logException (ex, "IncomingChatMessage ");}}
Www.networkcomms.cn
Www.cnblogs.com/networkcomms