C + + server Design (vii): Chat system service-side implementation

Source: Internet
Author: User

In the previous chapters, we analyzed the design and implementation principles of the service-side system, in which we use the server-side framework to implement a chat system that runs in the intranet environment. The chat system consists of two parts: client and server, and the service side maintains the user's account information through the database. This chapter will focus on how to use the server-side framework to develop the business logic of servers.

Chat system function Analysis

This chat system is only used as a service-side framework to display, so limited to the most basic LAN chat tools, data transmission is used as plaintext, not in-depth discussion on security. The specific functional requirements are analyzed as follows:

    • L User registration: Provide new user account registration function, the registration content includes the new user's account name and password. The server needs to detect the validity of the registration information and save the registered user's information in the database.
    • User login: User login According to the account password, if no login operation will not have permission to request chat-related messages. The server queries the database to verify the user's account information and to determine if the user has logged in. User account does not allow duplicate logins.
    • Online Friend Update: Logged-in users can proactively query the server for current online friend information. The server should also promptly push friends online and offline with all logged-in users.
    • L Friends Chat: Logged-in users can send chat messages to any friends who are online and receive messages from other online status friends.
    • Group chat: Logged-in users can send group chat messages to all online friends at the same time. You can also receive group chat messages from friends who are from other online states.
Implementation of database in chat system server

The chat system needs to maintain the user's account information, record the registered new account, and verify the user information of each login. We use the lightweight MySQL as the database management system, and choose mysql++ as the MySQL API Operation library.

The entire chat system has only built a structure named UserInfo table, as shown in table 5-1. At the same time, according to the mysql++ encapsulated two operating interfaces, add new user account information, and based on the account name and password to query whether the user exists.

Table 5-1 user account information table UserInfo

Field name

Data type

Key words

Constraints

Meaning

Id

Int (20)

Y

Unique

Unique identifiers

Username

varchar (20)

N

Unique,not NULL

Account name

Password

varchar (20)

N

NOT NULL

Password

Because database operations involve network transport and disk processing, this is a time-consuming operation. All processing in the server-side framework reactor reaction pool must be done in a non-blocking environment, and if the time-consuming operation will block the current thread, other message events are not processed in a timely manner. Therefore, database operations in reactor should be done asynchronously, and time-consuming operations such as databases can be handled by creating a worker thread pool. However, in this chat system, database operations are only involved in two scenarios in which a new user and a user are registered. To simplify the development model, we call the database-related operations directly here.

The database section is not the focus of this article, so no further introductions are made.

Chat device types and message event implementations

By analyzing the functional requirements, we can learn that there are two main kinds of message requests in the client connection, namely the temporary state and the login state. In a temporary state, you need to be able to request the registration of new users and login operations, you need to be able to request the current online user information, send a message type and broadcast message type to a user. And because of the mechanism of login timeout for the server, the client connection must send the heartbeat message to the server periodically, regardless of whether it is in a temporary or logged-in state.

The two states of the client correspond exactly to the two device types developed by the server-side framework, namely, the temporary device type and the logon device type. As shown in 5-1. We add a new registered account message event for the temporary device, which is used to register with all customers who have established a connection with the server. At the same time we create a new device type, called the Chattype device type, and inherit from the logon device type, which specializes in handling post-logon and chat-related message events.

Figure 5-1 Chat device types and message events

Temporary device types The newly added message events are described below:

    • L REGISTERUSR: Register a new user account. The client needs to pass in both the expected registered account name and password when requesting the message event. After the server receives the message event, officer Verify that the account name and password are legitimate, and then call the database new account registration interface for account registration. Finally, the registration result information is sent to the client based on the actual insert result of the database. Because the message event does not require permission, any customer who connects to the server can register the operation. In order to prevent the existence of some customers malicious registration phenomenon, in the actual implementation of the addition of the invitation code information. The server will verify that the invitation code from the client is correct, and if the invitation code is correct, the registration will be performed.
    • L HEARTMSG: Heartbeat message. The client sends a heartbeat message on a regular basis. After the server receives the message event, the time-out information for the connection is updated in the timeout queue. In an event callback implementation, the message is not further processed and returned directly.

Chattype for the newly created device type that inherits from the default logon device, the specific message event that is implemented is described below:

    • L Askfriends: Request the current online user information. The client requests the message event to the server after the login is successful. After the server receives the message event, it will query the user information for all other current online chattype types except the requestor, and collate the messages to the client. This data is used for client initialization of the online user list.
    • L Chatsend: Send a chat message to a designated online user. The client will send the content of the chat message, its own information, and the user information expected to receive the chat message to the server. After the server receives the message event, it tries to find the receiving user, forwards the chat message and sender message to the receiving user, and returns the Send Success message event to the sending user. If the receiving user is not online, only send failed message events will be returned to the sending user.
    • L Groupsend: Send chat messages to all online users. The client will send the chat message and its own information to the server. When the server receives the message, it will traverse all other currently online chattype types except the requestor, and forward the chat message and sender information to all traversed users and return the message to the sending user for success.
    • L HEARTMSG: Heartbeat message. The heartbeat message of the newly added heartmsg with the temporary device.
Life cycle implementation of chat devices

Although we have developed a specific device type and message event for the chat client connection, some business logic related to the connection state still needs to be designed. For example, how to make a specific login process related to the chat client? When a chat client has successfully logged in, how to notify other clients the first time the account is online? When a chat client exits, how do you notify other clients that the account is offline? These client state-related operations depend on the connection lifecycle mechanism developed in the previous section for management.

Figure 5-2 The life cycle of a chat device

The connection life cycle implementation of the specific chat device. We only need to rewrite the implementation of a specific business-related lifecycle interface, so the life-cycle interfaces that do not need to be changed are not listed. The interface implementations that need to be rewritten are described below:

  • L onlogincheckmsg (): This interface is executed when the client performs a logon operation and chooses the login type as the Chattype device type. At this time the system will check whether the client's account name and password is legitimate, if the legal will call the Database Account password query interface, determine whether the account exists. If the account exists, returns true and gives control back to the system for further login operations, and if the account does not exist, sends a message to the client that does not have the account information, the login failure, and directly returns false to exit the entire logon operation.
  • L onloginsuccessmsg (): When the logon operation is performed by a client with a login type of chattype, execution onlogincheckmsg () returns true and the entire system logon process succeeds and the interface is executed. At this point, the system will be two pieces of work: First send a successful login message to the client, followed by a user other than the user's own chattype type of login, and send a notification message to those users that the new user is online. In this way, each logged-on user only needs to request all current online user information to the server at the first logon, and the new user's offline or old user downline will be actively pushed by the server without requiring the client to periodically request maintenance.
  • L onloginfailuremsg (): When the logon operation is performed by a client with a login type of chattype, execution onlogincheckmsg () returns True, but the entire login process fails when the interface is executed. In general, the interface is executed to indicate that the user account has been logged in and the server cannot repeat the login operation for the same account. At this point the server will send a duplicate login to the client, this login failed message, and exit the entire logon operation.
  • L onlogoutmsg (): This interface will be executed when a client with a login type of Chattype is logged off. The server returns a successful logoff message to the client and further logoff of the connection.
  • L Releaseconnnode (): The interface is executed when a client with a login type of Chattype is logged off successfully, or if the connection is forced to exit due to a timeout or other exception reason. At this point the server will traverse other users who have logged in Chattype other than the user itself, and send a notification message to those users indicating that the user is offline. At the same time, the system will be the user connected to the requested resources to release the work.
  • L Onovertime (): When the server does not receive a valid message or heartbeat message for the client for a period of time, it will be sentenced to time out and execute the interface. This interface is typically executed to indicate that the client has stopped working due to an exception, but is not actively disconnecting. At this point the server will attempt to send a message to the client that the connection has timed out. Because the client is already in an abnormal state, there is no guarantee that the message can be received by the client. The server then executes the Releaseconnnode () interface and forces the client connection to be disconnected.
Chat system Show

The chat system is deployed in the LAN and can be operated by a client implemented in C #. The running scenario is as follows:

Figure 5-3 Login and Registration window

5-3 the login window for the client and the registration window. The registration window is opened by the registration button of the login window and the registration of the new account can be done. At the same time login window can be login operation of account, if login failure will show the specific failure reasons, if the login is successful, will go to the client main interface.

Figure 5-4 Main interface and Friends Chat window

5-4 is the client's main interface and Chat window. The current login username and the current online user name and number are displayed in the main interface. You can click a specific user name to enter the chat window with that user. In the Chat window, you can enter a message in the input field and click the Send key or press ENTER to send the message. If you receive a chat message from another user, the client will also actively pop up the user's Chat window and display the chat message received. There is also a group chat button at the bottom of the main screen, click to enter the Group Chat window.

Figure 5-5 Group Chat window

5-5 is the Group Chat window. In the Group Chat window, you can receive chat messages sent by other users who have opened the window. You can also enter related chat messages and send them to all other users under that window.

C + + server Design (vii): Chat system service-side implementation

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.