Online game communication model

xiaoxiao2021-03-06  41

Preface

Online games, as a product that combines the game and the network, bringing players into the new entertainment. Online games in China have also developed in China, and only 3, 4 years of history, and online games are still very young compared to single-machine games that have already developed history for decades. Of course, its formation is also based on historical changes, and there is no income of the Internet. As a new product, the development of online games is more mysterious about the developers. For an unknown area, developers may need to know what is the difference between online games and ordinary stand-alone games, how to connect the players, and How to provide a player with an interactive entertainment environment. This article will surround these three topics to tell you about the network interconnection method of online games. Online games and stand-alone games

When it comes to online games, I have to let people think of stand-alone games. In fact, the essence of online games can not be unique. The difference between online games and stand-alone games can be very straightforward: Isn't it possible to connect? ? That's right, but how to implement these features, how to make a reasonable integration of the network connection to the single game, is what we have to discuss below. Before you understand the specific implementation of the Internet, let's take a look at the individual running processes and online games. Only by knowing this, you can go deep into the core of online game development.

Let us first let us look at the simplified implementation process of ordinary single game:

Initialize () // Initialization Module {Initialization Game Data;} Game () // Game Cycle Section {Draw Game Scene, Characters, and Other Elements; Get User Operation Input; Switch (User Enter Data) {Case Move: {Treat Character Mobile } Break; Case attack: {Processing attack logic:} Break; ... other process response; ... default: Break;} Game NPC and other logic AI processing;} exit () // game end {Release game data Leave the game;}

Let me illustrate the flow of the upper alone game. First of all, whether it is a game software or other application software, the initialization part is essential, here you need to initialize the data of the game, including images, sounds, and some necessary data. Next, our game is looped to the scene, characters, and other elements, showing the game world to the player, and receives the player's input operation, and responds according to the operation. In addition, the game needs to NPC and some logic AI. Treatment. Finally, the game data is released, the game is over. There is a significant difference between online games and stand-alone games, which is a server for connecting all users in addition to a user interface platform (such as single game) for operation games, and provides data services for all users, From some point of view, the game server is like a large database, providing data and data logic interaction. Let's take a look at a simple online game model execution process:

Client computer:

Login () // login module {initialization game data; get the user and password entered by the user; create a network connection with the server; send it to the server for user authentication; ... Waiting for the server to confirm the message; ... get the server feedback login message IF (established) enters the game; ELSE prompts the user to log in error and re-accept the user login;} Game () // Game cycle part {Draw game scene, characters, and other elements; get user operation input; send users to the server to the server ; ... Waiting the server's message; ... receive feedback information of the server; Switch (Message Data of Server Feedback) {CASE Local Player Mobile message: {IF (allow local player mobile) Client to process people's movement; Else Customer The machine maintains the original state;} Break; Case other player / NPC mobile message: {Other players or NPC mobile processing according to the feedback information of the server;} Break; Case new player joins the game: {Add this in the client Players;} Break; Case players leaving the game: {Destroy this player data in the client;} Break; ... other message type processing; ... default: Break;}} EXIT () // Game end {send leave Message to the server; ... Waiting for the server to confirm; ... get the server confirmation message; disconnect with the server; release the game data; leave the game;} server:

Listen () // Game Server Waiting for the player connection module {... Waiting for the user's login information; ... receive user login information; analyze if the username and password are compliant; if (conformity) {Send a confirmation allowed to enter the game message to customers Machine; put this player into the game message to all players in the scene; add this player to the server scene;} else {Disconnect the connection with the client;}} game () // Game server loop section {.. . Waiting for the player's operation input; ... receives a player's mobile input or NPC mobile logic input; // This player / NPC is used as an example to perform logic judgment that the player / NPC is movable;

IF (movable) {Move the player / NPC to the server; send the mobile message to the client; send this player's mobile message to all players on the scene;} Else Send an unmovable message to the client;} exit () / / Game Service = Merger End {Received Players Leave Messages; Send this message to all players in the scene; send the information allowed to leave; deposit the player data into the database; log out of the data in the server;}}

Let us explain the operation mechanism of the simple online game model. Let's talk about the server side, here the server is divided into three parts (actually a complete online game far more than this): login module, game module, and logout module. The login module is used to listen to the network connection message sent by the online game client and verify its legitimacy, then create this player in the server and lead the player to the game module; the game module provides the player's actual application service, We will introduce this section in detail; after getting the player wants to leave the game, the logout module will remove the player from the server and save the player's attribute data into the server database, such as: Experience, Level, Life value, etc.

Let's take a look at the client of online games. At this time, the client is no longer like a stand-alone game. After initializing the data, you can enter the game directly, but to create a connection with the server, and enter the game before the license is obtained. In addition, the client game process of online games needs to communicate with the server, and the status of the current game is determined by switching data with the server, such as the position of other players, the item drop. Similarly, when leaving the game, the client will inform the server to leave the player user to make the server proceed accordingly.

The above use simple pseudo code to elaborate the execution process of stand-alone games and online games, and everyone should clearly see the differences between the two, and between the two mutual relationships. We can consider it, the online game is to move the logical arithmetic part of the stand-alone game to the game server and then return the processing result (including other player data) to the player to the connected player through the game server. Network interconnection After understanding the basic form of online games, let us enter the real actual application part. First of all, as a online game, in addition to the things necessary for the conventional stand-alone game, we also need to add a network communication module. Of course, this is the main part of the online game, let's discuss how to implement the network communication module.

A perfect network communication module involves fairly wide, this article is only discussed for more basic processing methods. Online games are composed of clients and servers, and there are two different network communication processing methods, but we have the same place, we will introduce their common point. We use Microsoft Windows 2000 [2000 Server] as a development platform, and use Winsock as a network interface (probably some friends will consider using DirectPlay to make network communication, but for current online games, DirectPlay is not suitable, specific reasons are not available here Discussed).

After determining the platform and the interface, we start some of the necessary initialization work before the network connection creation, whether it is a client or server. Let's take a look at the code snippet below:

Word wversionRequested; WSADATAWSADATA; WVERSIONREQUESTED MAKEWORD (1, 1); IF (WSAStartup (WinsionRequested, & WSADATA)! 0) {Failed (Winsock Version Error!);

By calling Windows Socket API functions, the network device is initialized, and then the creation of network sockets, the code snippet is as follows:

Socket SSocket Socket (AF_INET, M_LPROTOCOL, 0); if (SSOCKET == Invalid_Socket) {failed (Winsocket Create Error!);

Here, the number of Socket connections required for the client and the server is different. The client only needs a socket connection to meet the needs of the game, and the server must create a Socket connection for communication for each player user. Of course, it is not to say that if there is no player on the server, it does not need to create a socket connection. The server side generates a special socket when starting, and the player can create a request for the server to respond, and wait for the network listening part. There is more detailed description.

Initialization and creation inevitably release and delete, let's take a look at the release below:

IF (SSOCKET! = INVALID_SOCKET) {CloseSocket (SSOCKET);} if (wsacleanup ()! = 0) {Warning (Cant Release Winsocket);

The two steps here are all released accordingly for the initialization of the creation of the previous.

Next, look at a network execution process of the server side. Here we assume that the server has created a socket for use, what we have to do is to let this socket becomes a dedicated interface that listens to the network connection request, see the following code snippet:

SockAddr_in addr; Memset (& addr, 0, sizeof (addr); addr.sin_family = AF_ITDR = HTON_ADDR.S_ADDR = HTONL (INADDR_ADDR_Addr); // port); // port is the port number to listen // Bind Socketif (bind (SSocket, (SockAddr *) & addr, sizeof (addr) == SOCKET_ERROR) {failed (Winsocket Bind Error!);} // Listening IF (Listen (SSOCKET, SOMAXCONN) == Socket_ERROR ) {Failed (Winsocket Listen Error!);} This is the blocking communication process. At this time, the program will be in the state of waiting for the player user connection, if there is a client connection in this time, it is created to create it through accept (). The Socket connection of the player users, the code snippet is as follows:

SockAddraddrserver; Int Nlen SizeOf (AddRServer); Socket SPlayersocket Accept (SSOCKET, & Addrserver, & Nlen); if (splayersocket == invalid_socket) {failed (Winsocket Accept Error!);

Here we create a splayersocket connection. After that, the game server and the player user have passed this socket. So far, our server already has the function of accepting player users, let us see how the game client is connected. To the game server, the code snippet is as follows:

SockAddr_in Addr; Memset (& addr, 0, sizeof (addr); addr.sin_family = AF_INET; // To connect the game server port number addr.sin_addr.s_addr = inet_addr (ip); // To connect the game server IP address Addr.sin_port = HTONS (port); // To this, the client and server already have a bridge of communication, // Next is the transmission and reception of data: Connect (SSOCKET, (SockAddr *) & addr, sizeof Addr); if (SEND (SSOCKET, PBUFFER, LLENGTH, 0) == Socket_ERROR) {failed (Winsocket Send Error!);

The PBUFFER here is the data buffer pointer to be sent, and LLEngth is the length of the data that needs to be sent. Through this Socket API function, we can send data from the client or server, and we can pass RECV () This Socket API function is received:

IF (RECV (SSOCKET, PBUFFER, LLENGTH, 0) == Socket_ERROR) {Failed (Winsocket Recv Error!)

Where PBuffer is used to store the acquired network data buffer, LLEngth is the length of the data that needs to be acquired.

Now, we have already understood the basic knowledge of network interconnects, but as online games, such a simple connection method is unable to meet a hundred people in online games online, we need more reasonable tolerance and stronger network communication processing method Of course, we need to know what the online game needs for network communication. Everyone knows that the game needs to continue to loop the logic in the game and draw the game world. The Winsock handles described above is carried out in a blocking method, which in violation of the implementation of the game, can be imagined, connected to the client During the server, your game cannot be controlled, then if the player wants to cancel or do other processing, even display a most basic dynamic connection prompt can't. So we need to use other ways to handle network communication, so that it will not conflict with the game main line, you may think that you can create a network thread to handle it? That's right, we can create a sub-thread specifically for network communication to solve this problem. Of course, we have a thread in our game. We need to do more considerations, let us see how to create a network communication thread.

In the Windows system, we can make threads created through the CreateThread () function, see the following code snippet:

DWORD DWTHREADID; Handle Hthread = Createthread (Null, 0, Netthread / * Network Club Fingers * /, SSOCKET, 0, & DWTHREADID); if (hthread == null) {Failed (Winsocket Thread Create Error!);

Here we have created a thread while incorporating our Socket in thread:

DWORD WINAPINETTHREAD (LPVOID LPARAM)

{Socket Ssocket (Socket) LPARAM; ... RETURN 0;

Netthread is our network thread we used to handle network communications. So, how do we introduce Socket's processing into threads?

Take a look at the code snippet below:

HANDLE hEvent; hEvent = CreateEvent (NULL, 0,0,0); // Set asynchronous communication if (WSAEventSelect (sSocket, hEvent, FD_ACCEPT | FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE) == SOCKET_ERROR) {Failed (WinSocket EventSelect Error! }

After the above settings, the Winsock API function will run in a non-blocking method, that is, return immediately after the function is executed, and the network communication will be stored in HEVENT in the event without parking the entire branch.

After completing the above steps, we need to respond and process on the event, let us see how to get the event message generated by network communications in the network thread:

WSAEnumNetworkEvents (sSocket, hEvent, & SocketEvents); if (SocketEvents.lNetworkEvents = 0!) {Switch (SocketEvents.lNetworkEvents) {case FD_ACCEPT: WSANETWORKEVENTS SocketEvents; break; case FD_CONNECT: {if (SocketEvents.iErrorCode [FD_CONNECT_BIT] == 0) // Connect the success {// Connection successfully notified the main thread (game thread) for processing}} Break; Case FD_READ: // Get Network Data {IF (RECV (SSOCKET, PBUFFER, LLENGTH, 0) == Socket_ERROR) {Failed (Winsocket Recv Error!);}} Break; Case FD_WRITE: BREAK; CASE FD_CLOSE: // Notify the main thread (game thread), the network has disconnected Break; default: Break;}} Only network connections (FD_CONNECT) and Read data (fd_read) performs a simple simulation operation, but after receiving the event message, the network thread will organize the data to organize the data, then return the data back to our game main thread, the game main thread will process The data sent out, such a round-trip constitutes data communication in our online game, is the most basic element that makes online games.

Finally, let's talk about the organization of the network packet (data package), the online game data package is the most basic unit of the game data communication. The online game generally does not use the word throttle to perform data transmission, one data package package It can also be seen as a message instruction, in the game, the server and the client will continue to send and receive these message packets, and then convert the message package parsing to the command meaning and execution. Interactive and management

Speaking of interaction, for the player's communication with other players, but for the computer, the interaction is interacting is the mutual transfer of data messages. As we have learned about the basic concepts of network communication, it constitutes the most basic condition of interaction, and we need to communicate data on this network level. Unfortunately, the computer does not know how to express communication between players, so we need to provide a set of instruction organizations and parsing mechanisms that can make computer understanding, which is the network packet (data package) of us above. Processing mechanism.

In order to be more simple to explain the organizational form of network packets, we discuss with a chat processing module to see the following code structure:

Struct tagMessage {long LTYPE; long lplayerid;}; // message instruction // instruction-related player identifies char strtalk [256]; // message content

Above is an extremely simple message package structure, let's talk about the use of its various data domains:

First, LTYPE is the type of message instruction, which is the most basic message identifier, which is used to tell the server or the client's specific use to facilitate the server or client. Lplayerid is identified as a player. Everyone knows that a player is actually a bunch of data inside the machine, especially in the game server, there may be thousands of players, at this time, we need a tag to distinguish the player, so you can quickly find a specific player. And apply communication data to it. Strtalk is the chat data we have to pass. This part is a real data entity. The front parameters are only limited by the data entity application.

After the data is organized, it is followed by transmitting this structural data through the Socket connection. Here we have to understand, the network is in the data transmission process, it does not care about the data structure adopted by the data, which requires us to convert the data structure into a binary data code to send, in the recipient, we will convert these binary data codes The corresponding data structure used in the process. Let's take a look at how to achieve:

TagMessagemsg; msg.ltypemsg_chat; msg.lplayerid 1000; strcpy (& msg.strtalk, chat information);

First, we assume that a packet has been organized, here MSG_Chat is the identifier of our own self-definition, of course, this identifier is unified in the server and client. The player's ID is set according to the game needs. Here 1000 is used as a hypothesis, now continue:

Char * p = (char *) & msg; long llength = sizeof (tagmessage); send (SSocket, P, LLEngth); // Get the length of the data structure

We convert the structure into a CHAR type data pointer by an forcibly converting, so that the flow data processing can be performed by SizeOf (), and then use the Winsock's send () function to send out the data. .

Next, look at how to receive data:

Long LLENGTH = SIZEOF (Tagmessage); Char * Buffer = New Char [LLENGTH]; RECV (SSOCKET, BUFFER, LLENGTH); tagMessage * p = (tagMessage *) Buffer; // Get data

After obtaining network data through the RECV () function through Winsock, we also convert the obtained buffer data into the corresponding structure by forced conversion, so that the data can be easily accessed. (Note: Forced conversion only as a means of data conversion, there are more optional methods in practical applications, here only for simple description logic), have to mention how servers / clients can filter each A message and how to manage the communication packet. Whether it is a server or a client, when the network message is received, after the above data is parsed, the message type must be screened and failed. Simply, it is a message loop similar to Windows, and the different messages are different. This can be used through a Switch statement (familiar with friends who are familiar with the Windows message loop.), Based on the LTYPE information in the message package, the message is derived, considering the following code segment:

Switch (P-> LTYPE) // The p-> LTYPE here is the message type identifier {case msg_chat: // chat message Break; Case MSG_Move: // Player Mobile Message Break; Case Msg_exit: // Player Leave Message Break; default: Break;} MSG_MOVE and MSG_EXIT in the upper segment are our virtual message identifiers (I have hundreds of identities in a real game, which requires consideration of optimization and priority message processing issues). In addition, a network gaming server faces hundreds of thousands of connection users, we also need some reasonable data organization management methods to perform relevant processing. Ordinary monomer gaming servers may cause the entire game network to be paralyzed because it is too much, and this is introduced into the packet server mechanism, we separate the server to distributed processing.

We extract each module to make a dedicated server system, then build a data center to connect all servers to perform data interaction, where each module creates a connection with the data center, ensuring the correlation of each module, At the same time, the player transforms to connect to the server that is currently providing the service, so that the burden on a single server can be alleviated, disperse the pressure into multiple servers while ensuring the unity of the data, and even if a server is abnormal. And when it does not affect the game players of other modules, thereby increasing overall stability.

The grouping server mitigates the server's pressure, but also brings server scheduling issues. The group-based server needs to process server jumps. Take a player's game scene jump as a foundation foundation: Assume some players in the game scene A, He wants to jump from the scene A to the scene b. In the game, we call the scene to change. At this time, the player will trigger the jump demand, such as walking to the switching point in the scene, so the server will put the player data from the game scene A The server is deleted, and the player is built in the game scenario B server.

The simple model of scene switching is described here, and there are many steps in the process, but it is believed that you can derive a lot of application skills. However, it should be noted that when the scene switch or inter-module switches, it is necessary to consider the transmission safety of the data and logic rationality, otherwise the switch is likely to be a bridge for future players to replicate items.

to sum up

This story tells through some simple processes to communicate online game communication, providing a way of making a production, although there are many things to do, but as long as this idea is expanded, we will be perfected, I believe everyone is very fast. You can write your own network communication module. Due to time rush, this article is omitted in many details, and if there is a mistake in the text, it is also forgiven.

转载请注明原文地址:https://www.9cbs.com/read-75539.html

New Post(0)