A multiplayer online chess and card online game project is coming to an end. I participated in the entire design process of the project and completed the core of 90%.Code. There are many things worth chatting about this project. This series does not plan to elaborate on how detailed the project will be. It should be described in the design document. I plan to only talk about some worth noting.
A special feature of this project is that the client is a mobile phone, and the user communicates with the server through the mobile network. Compared with PCs, mobile phones have weak processing capabilities and are expensive in terms of network traffic. In addition to some common online game problems, these two issues need to be fully considered in the design.
The first is the selection of development languages. Since the server is a Linux environment, Ms technology is directly excluded. As for mono, I am not at ease. The options are c ++ and Java. Java is better than the powerful network capability and short development cycle. It supports many frameworks and open-source libraries, it is not easy to write unacceptable code; C ++ is faster than speed. Based on various factors, C ++ makes it easier to turn this project into a bunch of code nightmares. We chose Java.
I. Network
The first problem for online games is, of course, how to communicate over the network. The first thing we should consider is the HTTP protocol. Because all the mobile phones of the agent support this protocol, we certainly want to be as compatible with users as much as possible. In addition, HTTP protocol encapsulation is already very high, so you don't need to consider threads, synchronization, status management, and connection pools. However, HTTP protocol has two unpleasant aspects:
◇ The protocol is stateless, which has plagued many people many times. The solution I have considered is to transform the HTTP protocol and do not close the socket after the data transmission is complete. However, the workload is very heavy. in the project cycle, it is basically mission impossible, not considered. Then, the customer can only request data from the server through polling.
◇ Excessive network traffic. For this project, only commands are transmitted between networks, but a bunch of useless HTTP headers need to be added for each transmission, and the client needs to perform polling, this traffic is terrible for mobile phones. After a simple test, according to the 0.03 RMB/k gprs network fee calculation, a Board card actually consumes more than 1 RMB (polling per second ), it is unacceptable. Maybe we can use the traffic and monthly charges, but this topic has nothing to do with technology.
The above problem leads us to select socket, which means we will not have a web environment and many things should be implemented by ourselves: thread management, customer status monitoring, Object pool, console ..........
The Network part is intended to be implemented using Java NiO, which is a new network listening method. Event-based Asynchronous Communication can improve performance. After each client is connected, an independent socketchannel will communicate with it. This socketchannel will exist throughout the user's lifecycle. If the user disconnects, the server will get-1 and throw a Connection Reset exception. By capturing these two features, you can clear related resources after the user accidentally disconnects. Since NiO is an asynchronous communication, there is no complicated thread management.
Ii. Communication Protocol
This project does not have complex communication commands, and the number of commands is very limited, but there is still a key issue to be concerned: traffic. To minimize the traffic, we use bytes instead of strings to save system commands, which can reduce the traffic by half. For example, we use one byte to save a playing card, and the byte height indicates the color, the low byte level indicates the number. If 0 represents the black peach, then the black peach 3 should be 0x03. This requires bitwise operations:
Int m = 0;
Int n = 3;
Byte card = (byte) (m) <4) | (byte) N; // M shifts four places left and then operates with N
In the game, you need to pass the user's points. This is a big integer. it is safer to use four bytes to save. The operation to convert an integer to four bytes is as follows:
Public static byte [] translatelong (long mark)
{
Byte [] B = new byte [4];
For (INT I = 0; I <4; I ++)
{
B [I] = (byte) (Mark >>> (24-I * 8 ));
}
Return B;
}
The operation to convert the four bytes back is as follows:
Public static long translatebyte (byte [] B)
{
Int mask = 0xff;
Int temp = 0;
Int res = 0;
For (INT I = 0; I <4; I ++)
{
Res <= 8;
Temp = B [I] & mask;
Res | = temp;
}
Return res;
}
Iii. Database Connection Pool
Because there is no web environment, we need to implement a database connection pool by ourselves. Apache has a project called commons DBCP, which is based on Apache's own object pool (APACHE commons pool) we can use the implemented database connection pool directly. Apache software may not be the best, but it may be much better than what we write.
Commons DBCP requires three. jar:
Commons-collections-3.1.jar, commons-dbcp-1.2.1.jar, commons-pool-1.2.jar
All three files can be downloaded from the Apache-Jakarta-Commons project and added to the project.
The code for constructing a database connection pool is as follows:
Import java. SQL .*;
Import com. gwnet. Games. antilord. util .*;
Import org. Apache. commons. DBCP. connectionfactory;
Import org. Apache. commons. DBCP. basicdatasource;
Import org. Apache. commons. DBCP. cececonnectionfactory;
Private Static basicdatasource BDS = new basicdatasource ();
Private Static connectionfactory FAC = NULL;
// Initialize the connection pool
BDS. setdriverclassname ("org. PostgreSQL. Driver"); // The database driver.Program
BDS. seturl ("JDBC: PostgreSQL: // localhost: 5432/mydb"); // Database URL
BDS. setusername ("Postgres"); // DBA account
BDS. setpassword ("XXXXXXXX"); // Password
BDS. setinitialsize (100); // number of initial connections
BDS. setmaxidle (10); // maximum number of idle
BDS. setmaxwait (1000*60); // timeout recovery time
FAC = new cececonnectionfactory (BDS); // get the connection Factory
Connection conn = FAC. createconnection (); // obtain the connection from the pool
Conn. Close (); // release the connection and return to the pool.
// Destroy the connection pool
BDS. Close ();
BDS = NULL;
FAC = NULL;
Handle various exceptions on your own.
Iv. Generation of playing cards
In the game, we need to generate random cards for users. First, we need to initialize a deck card and put it in a hashmap. Each card is represented by one byte. The height indicates the color, and the height indicates the number, generate the secondary card:
Private Static hashmap cards = new hashmap ();
Int TMP = 0;
For (INT I = 0; I <4; I ++ ){
For (INT m = 0; m <13; m ++ ){
TMP = (byte) (I) <4) | (byte) M); // construct a card using a bit operation
Cards. Put (New INTEGER (I * 13 + M), new byte (byte) TMP ));
}
}
Cards. Put (New INTEGER (53), new byte (byte) 0x4d); // dawang
Cards. Put (New INTEGER (54), new byte (byte) 0x4e); // John
How to obtain n cards randomly? Our practice is to generate a random number ranging from 0 to 55. Use this random number as the primary key to obtain the object from hashmap. After obtaining the random number, delete the object from the queue to avoid repeated acquisition. Since the random numbers in Java are generated based on time, it may lead to insufficient cards for users. Is it a joke that every user can find a train? Therefore, when a random number is generated, we add a large prime number for calculation:
Long cardid = new long (math. Round (math. Random () * 87) % 55). intvalue ();
By modifying this large prime number, you can better control a user's card.
V. threads
In fact, the system does not have complex thread management, but I want to provide a console for administrators to manage the main thread of the game and enable it to stop, center, recover, and restart, the original design was that the Administrator managed to manage main thread B by dealing with thread a and using thread A. But friends familiar with Java threads know that thread management is basically impractical, for example, how does a destroy B? Maybe you will say that calling the destroy () method of B is fine. This is also true for a lot of information about Java threads on the Internet, but they are all bullshit. Let's look at java.Source codeThe actual code for the thread. Destroy () method is as follows:
Public void destroy ()
{
Throw new nosuchmethoderror ();
}
The truth is that the thread. Destroy () method has never been implemented from start to end. All writesArticleAll the people who use this method to destroy the thread hit the wall.
The best solution is that A is responsible for generating a B and starting it, and B manages the lifecycle by itself. A and B communicate by using a shareable method, which is recommended by Sun.
6. asynchronous messages
Many items need to be recorded during a user's card playing process, such as recording Users' points, level changes, recording card play logs for data statistics, etc. When there are many users, recording this information in the database will consume a lot of resources, and users may wait for a long time after playing the game. To solve this problem, the message Bean of J2EE is used to provide an asynchronous communication mechanism. When data needs to be recorded, the system encapsulates a value object and sends it to the J2EE container, this operation is fast and will be returned after completion. You can continue the operation without worrying about when the message will be processed.
The message framework of J2EE has the following features:
◇ The message will be read only once. The JMS framework has its ownAlgorithmTo buffer messages to the hard disk. Even if the J2EE server dies, messages will not be lost.
◇ The system uses a point-to-point queue message queue to ensure that messages of the same priority are FIFO.
In JBoss 4.0, deploying message beans and queue queues is easier than WebLogic 8.1. declare the Message destination in XML. If JBoss finds that the destination does not exist, it will automatically create one, which is very simple.
7. Start and exit
To make the system have satisfactory performance, we should try to reuse as many objects as possible to reduce the number of new objects created. For example, for the message sending mentioned above, our operation is to provide a static class, which is initialized at system startup to maintain the connection with the JMS server. When the system sends a message, you do not need to query the JNDI and generate the queueconnectionfactory, which improves the system response speed.
In terms of the database connection pool, we also use the same operation to initialize n connections at startup. However, if you do not perform any operation when closing the process, the JMS will throw a socket exception. Although there is no major impact, it is always unprofessional and the connection in the pool will not be released, it may also cause problems. It is best to allow the system to perform operations after Ctrl + C like console programs such as JBoss, release resources and exit. We can add a hook to the process/thread. Windows programmers should be familiar with this.
Hook should be a thread method, as follows:
Public class hook extends thread
{
Public void run ()
{
// Release the database connection and destroy the connection pool
// Close the connection with JMS
}
}
Add the following to the main thread:
Runtime. getruntime (). addshutdownhook (new hook ());
Then, the process/thread will execute the hook run method when exiting to clear resources.