Tcp-based chat program breeze IM (c # Open Source ),

Source: Internet
Author: User

Tcp-based chat program breeze IM (c # Open Source ),

In breeze IM, if a user goes online, the user status is updated to the online status in the user list of other users. If the user goes offline, the user's profile picture will become gray.

 

Let's take a look at the relevant code:

First, the client code (1 ):

UserInfo userInfo = new UserInfo (); userInfo. userID = txtUserID. text. trim (); userInfo. password = txtPassword. text. trim (); // send the contract class to the server and obtain the returned result UserLoginContract loginContract = newTcpConnection. sendReceiveObject <UserInfo, UserLoginContract> ("UserLogin", "ResUserLogin", 8000, userInfo); // if the login succeeds if (loginContract. message = "success") {jump to the main window this. dialogResult = DialogResult. OK ;}

 

The server has the corresponding solution to login.

Registration Method:

 NetworkComms.AppendGlobalIncomingPacketHandler<UserInfo>("UserLogin", IncomingLoginHandler);

Solution:

// When a user logs on to the networkcomms framework, the received bytes are automatically deserialized into private void IncomingLoginHandler (PacketHeader, Connection connection, UserInfo) of the corresponding userInfo type) {try {// verify the logon information from the database UserLoginContract resContract = DoRcUsers. login (userInfo. userID, userInfo. password );
// Return the verification result to the client connection. SendObject ("ResUserLogin", resContract );

// If the client user successfully logs in, we add this user to the User Manager if (resContract. message = "success") {lock (syncLocker) {// log on to the same account. log out of the logged-on client first if (userManager. containsKey (userInfo. userID) {// if the user ID has been logged on, find the network connection corresponding to the user ID and close the connection,
// Closes the client user connection. an indirect method is used to send a message to the client user for automatic exit. The client user will exit after receiving the message. The heartbeat detection mechanism on the server will
// Check the connection that the client exits and delete it from the system.
Foreach (Connection conn in NetworkComms. getExistingConnection (userManager [userInfo. userID], ConnectionType. TCP) {conn. sendObject ("CloseConnection", "msg");} // if the user has logged on, delete the userManager. remove (userInfo. userID);} // register a new user and add the newly logged-in user to the User Manager if (! UserManager. ContainsKey (userInfo. UserID) {userManager. Add (userInfo. UserID, connection. ConnectionInfo. NetworkIdentifier) ;}// notify other users after the User goes online
// This method is used to notify other users that the current user has logged on. You can light up your avatar.
Userstatenovel (userInfo. UserID, true) ;}} catch (Exception ex) {LogTools. LogException (ex, "IncomingLoginHandler ");}}

Let's take a look at this method to notify other users.

// After the status of a client user changes, notify other users of private void userstatenoworkflow (string userID, bool onLine) {try {// user status contract class UserStateContract userState = new UserStateContract (); userState. userID = userID; userState. onLine = onLine; IList <strong guid> allUserID; lock (syncLocker) {// obtain the user IDs in all user dictionaries. users in the user dictionary are all OnLine users.
// AllUserID obtains the network ID of all users. Each client connection corresponds to a network ID that uniquely identifies a network connection.
AllUserID = new List <strong guid> (userManager. Values) ;}// send the online status foreach (strong guid netID in allUserID) to all users ){
// Obtain the network Connection List <Connection> result = NetworkComms based on the network ID. getExistingConnection (netID, ConnectionType. TCP); if (result. count> 0 & result [0]. connectionInfo. networkIdentifier = netID ){
// Send a notification to the network connection. When a new user is online and the new user information is displayed, the client lights up the user icon after receiving the message. result [0]. sendObject ("userstatenoworkflow", userState) ;}} catch (Exception ex) {LogTools. logException (ex, "MainForm. userstatenoworkflow ");}}

Let's take a look at the server User Manager.

// Online user Dictionary <string, Region guid> userManager = new Dictionary <string, Region guid> ();

<String, Region guid> string is used to store user IDs, and Region GUID is used to store the unique network ID corresponding to the current user's network connection. (Through this network ID, you can find the corresponding Tcp connection and send a message to the client through the connection ).

 

Let's look back at the Code related to a user's online message received by the client:

First, the client registers a user to publish a message.

  NetworkComms.AppendGlobalIncomingPacketHandler<UserStateContract>("UserStateNotify", IncomingUserStateNotify);

 

Solution

Private void incominguserstatenoworkflow (PacketHeader, Connection connection, UserStateContract userStateContract ){
// If the user is OnLine, if (userStateContract. OnLine) {lock (syncLocker ){
// Set the state attribute of this user. After the attribute is updated, the user State will be updated with the Common. getDicUser (userStateContract. userID ). state = OnlineState. online ;}} else {lock (syncLocker) {Common. getDicUser (userStateContract. userID ). state = OnlineState. offline ;}}}

 

 

Next, let's talk about the client user login. After logging in, we will jump to the main interface.

In the main interface window, obtain the list of my friends

Public void GetAllMyFriend () {// clear the Common dictionary before obtaining it. allUserDic. clear (); if (Common. allUserDic. count = 0) {// The user information sent to the server and obtained the result contains the user status UserListContract userListContract = Common. tcpConn. sendReceiveObject <string, UserListContract> ("GetFriends", "ResGetFriends", 5000, Common. userID); // traverses and loads friends foreach (UserContract user in userListContract. userList) {// Add the user to the dictionary // use different icons if (user. isMale) {Common. AddDicUser (user. UserID, new User (user. UserID, user. Name, user. Declaring, user. IsMale = true? UserSex. Male: UserSex. Female, Properties. Resources. q1, "phone", "email", user. OnLine = true? OnlineState. online: OnlineState. offline);} else {Common. addDicUser (user. userID, new User (user. userID, user. name, user. declaring, user. isMale = true? UserSex. Male: UserSex. Female, Properties. Resources. q2, "phone", "email", user. OnLine = true? OnlineState. Online: OnlineState. Offline ));}}}}

The processing code of the server:

First, register the processing method:

// The client obtains the friend list NetworkComms. AppendGlobalIncomingPacketHandler <string> ("GetFriends", IncomingGetFriends );

Solution:

// The client obtains the server-side processing method of a user's friend list. private void IncomingGetFriends (PacketHeader, Connection connection, string userID) {try {
// Obtain all IList <UserContract> userContractList = DoRcUsers. GetAllMyFriends (); UserListContract listContract = new UserListContract (userContractList); lock (syncLocker ){
// Traverse the User Manager on the server. if the user is online, set the user status to online (foreach (UserContract theuser in userContractList) {// determine whether other friends are online if (userManager. containsKey (theuser. userID) {theuser. onLine = true ;}} connection. sendObject <UserListContract> ("ResGetFriends", listContract);} catch (Exception ex) {LogTools. logException (ex, "IncomingGetFriends ");}}

 

/// <Summary> /// user information contract class /// </summary> [ProtoContract] public class UserContract {// user ID [ProtoMember (1)] public string UserID {get; set;} // user Name [ProtoMember (2)] public string Name {get; set;} // user description [ProtoMember (3)] public string Declaring {get; set;} // gender [ProtoMember (4)] public bool IsMale {get; set ;}// initial online status [ProtoMember (5)] public bool OnLine {get; set;} public UserContract () {} public UserContract (string userID, string userName, string underWrite, bool male, bool onLine) {this. userID = userID; this. name = userName; this. declaring = underWrite; this. isMale = male; this. onLine = onLine ;}}UserContract contract class // <summary> // list of user information, for example, you can pass all my friend information /// </summary> [ProtoContract] public class UserListContract {[ProtoMember (1)] public IList <UserContract> UserList {get; set ;} // The following code is mainly used to prevent the list from being empty. If the list is empty and the following code is not added, serialization may result in [DefaultValue (false), ProtoMember (2)] private bool IsEmptyList {get {return UserList! = Null & UserList. count = 0;} set {if (value) {UserList = new List <UserContract> () ;}} public UserListContract () {} public UserListContract (IList <UserContract> userList) {this. userList = userList ;}}UserListContract contract class

Now, the user login is basically clear

Www.networkcomms.cn

Www.cnblogs.com/networkcomms

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.