Use JAVA to build a stable multi-threaded Server

Source: Internet
Author: User
Use JAVA to establish a stable multi-threaded server-general Linux technology-Linux programming and kernel information. The following is a detailed description. Content:

Establishment of Message System
Server Structure
PORTListenThread
ClientSingle image class of a single client in the connection pool
Group
Master Server type Server
Summary
About the author

Hou Shi (wearebug@etang.com)


This article describes in detail how to use Java to establish a multi-threaded server. This server uses objects to transmit messages and queue mechanisms in the thread, greatly improving the server performance. This server can be used in applications with various C/S or B/S structures.
The Java language is fully object-oriented, and Its thread mechanism and Object serialization are especially easy to use. It is much easier to use Java to build a multi-thread server than to use other languages, if you make good use of its exception handling mechanism, you can create a commercial multi-threaded server. Message Queue and Socket transmission are used, so messages are not lost. This server can be used as a real-time chat server and collaborative server among multiple users.

Establishment of Message System

The message system of this server uses the object transmission mechanism, rather than the character string transmission that is often used previously. The advantage of object transmission is the convenience of extension. To create a new message, you only need to inherit from a unified base class, and then write your own implementation method. This is also in line with an important Principle in the Object-Oriented field: OCP (open_closed Principle), that is, a good design should be able to accommodate the addition of new features, however, the added method is not to modify the original class, but to add a new class.

First, create a base class: Msg, which has two fields sender and receiver respectively to record the message sender and receiver. These two fields are entered when the message class is constructed. The receiver domain can be empty, and the blank field indicates that all messages can be sent to, which is determined by the forwarding server. This class includes obtaining the values of these two domains and message processing functions. The message processing function process () is an empty function for the successor to overload.

After this abstract base class is created, you can inherit it to complete your own class. For example, if I want to build a group-based collaborative drawing system and support conversations between members, I can create the following class set:

SendTextMsg (String sender, String receiver er, String info) // send a conversation to a specified person.
AddLineMsg (String sender, Point a, Point B) // draw a straight line between a specified Point
AddRectangle (String sender, point start, Point end) // create a specified rectangle.
AddRotundaMsg (String sender, Point center, int radius) // create a specified circle
RemoveObjectMsg (String sender, int ID) // Delete the specified image object
......

You can also create many message classes. In each class, a process () method is used to process the message class. You can enter this method to process the message class, and the server is only responsible for forwarding the message. In this way, a message system is established.

Server Structure

If you want the server to implement services for each client at the same time, you need to use multiple threads to establish a thread pool. When a client is connected, a thread is opened in the pool to serve it. Similarly, to avoid the loss of a large number of messages when they arrive, you must use the message queue. This server is processed hierarchically.

The class relationship diagram is as follows:




The working process of the Server is like this. A Server class is established as the main class, which contains the main () function of the program's entry function (). Initialize an array in the constructor to store the ClientSingle class, which is actually a separate class for handling the connected users. Start a thread PORTListenThread. The thread is used to monitor whether a user logs on the port. When a user connects, the thread is sent to the addClient () of the Server for processing. The addClient () method of Server will create a ClientSingle object in the array just now, and then hand over the rest to it.

PORTListenThread

In the start part of the run () function, check whether serverScoket is empty to ensure that no error occurs at the beginning of the loop. Then enter an infinite loop listener:

While (true) {// dead loop monitoring
Try {Socket clientSocket = null;
ClientSocket = serverSocket. accept ();
Server. addClient (clientSocket); // transfer to Server for processing
}
Catch (IOException e) {System. out. println ("error listening port" + e);} // Display Error
}

ClientSingle image class of a single client in the connection pool

After each client connects to the server, the server will automatically create an image of the client in the connection pool, and all the operations will be handed over to the image for specific execution, therefore, ClientSingle must contain some basic information about the client. For example, the client name and logon time. In this class, there are two Message Queues: sendQueue (sending Queue) and receiveQueue (receiving Queue) cache messages.

The ClientSingle class inherits from the Thread and is still a caller. Start two subthread classes SingleSender and SingleListener during initialization. SingleSender is responsible for listening to commands in the sending queue. If yes, SingleListener is responsible for listening to messages that have arrived. If yes, it adds these messages to the receiving queue, which is processed by ClientSingle. Therefore, the main task of ClientSingle is to process the two queues. The two queues can be implemented using Vector, which is very simple.

// ------- Add a message to the sending queue ------------
Synchronized void send (Object o)
{SendQueue. add (o );
}

To stably control the running of sub-threads, the run () method is not encouraged to use true for the dead loop mark, but to use a Boolean variable finish. You can set this flag to false to stop the thread running.

After the sending sub-Thread class starts, execute the loop in run () (End mark with finish). In this loop, first determine whether the sending queue in ClientSingle is empty, if it is null, sleep for a certain period of time before re-judgment, this is also a while loop. If it is not empty, the system starts to process the message in the queue and extracts the message and puts it into the output stream for sending.

Public void run (){
While (! Father. finish) {// loop listener
While (father. v. isEmpty () {// when the sending queue is empty, the thread sleeps for 500 milliseconds
Try {Thread. sleep (500 );}
Catch (InterruptedException e) {System. out. println (e );}
}
If (! Father. v. isEmpty () {// when the sending queue is not empty
Try {
Object a = father. v. firstElement (); // retrieves the first message in the queue.
Father. v. removeElementAt (0); // Delete from queue
Oos. writeObject (a); // send the message
Oos. flush ();
} Catch (IOException e ){
DisplayMessage ("transmission failed! ");
Father. finish = false;
}
}
}
}

The SingleListener class for receiving subthreads is similar to that for sending subthreads, and their run () methods are similar. The difference is that the receiving subthread adds the received message to the receiving queue of ClientSingle for processing.

The run () method of the ClientSingle class reads the content in the receiveQueue of the receiving queue cyclically. If it is null, it waits. If it is not null, it extracts and forwards the content in sequence. The message processing function is processMsg (). It only executes the process () method of the message class. After processing, the Server class method will be called for various types of forwarding.

Group

To Group clients, I have created a Group class. There is a list in this class that stores the addresses of the ClientSingle classes that already exist in the connection pool. You only need to traverse the entire list to access members in all groups. This list can be implemented using a Vector or a hash table. I recommend the latter to allow access by name.

The Group object itself can also exist in the group list of Server classes.

The grouping function is very important for collaborative systems of multiple people, especially when groups operate on a shared space. Taking the above collaborative drawing system as an example, if three of the 10 people want to set up a new stove, the three of them cannot be seen by others, this requires a "group" division.

Master Server type Server

The Server class is the core class, which plays a global role in scheduling in this framework. All the classes described above are constructed and called in a unified manner.

The domain of the Server class includes a fixed-length array to store the ClientSingle instance, which is the implementation of the connection pool. There is also a hash table to store Group instances. The methods of the Server class are all operations on these two classes.

The objective of setting up a ClientSingle array is to ensure the stability of the server. In fact, you can choose not to create it, but to dynamically construct objects, but it is difficult to manage connected users, and because various operating systems process different processes, dynamic Creation of service threads is unstable. Therefore, I first create an array as the container for these objects and estimate the maximum number of connectors at the beginning. AddClient () function of the Server class:

Void addClient (Socket socket ){
Int c = 0;
Try {while (sch [c]! = Null) c ++;} // search for the free space in the array
Catch (ArrayIndexOutOfBoundsException e ){
Try {socket. close ();} // closes the slot connection due to an exception
Catch (IOException ee) {System. out. println ("array overflow ");}
Return;
}
Sch [c] = new ClientSingle (c, socket, father, this); // create a ClientSingle object in the searched position
}

The forwarding methods in the Server class include sendToAll (), sendToOne (), sendToGroup (), and so on. These methods are all operations on methods in the thread pool, which is relatively simple. They are all about finding a ClientSingle object in the thread pool and then calling its send () method.

Note: These forwarding methods may be called by many sub-threads at the same time. To ensure thread stability, remember to add the synchronized keyword before the method.

Summary

Through the above description, you can find that it is important to establish a stable server program, message queue and thread pool. In addition, many unexpected situations must be taken into account. Generally, programmers do not care after writing the thread's run () method loop. In fact, they should also consider the release of resources after jumping out of the loop.

This is just some of the preliminary experiences I have summarized in the compilation process, and I hope I can give them a reference.

About the author

Hou photosensitive graduated from the Computer Science and Engineering Department of Tianjin Institute of Technology. A company in Beijing is engaged in software development and uses java programming. You can contact me via wearebug@etang.com.

-- Taken from the IBM China website
Http://www-900.ibm.com/developerWorks/cn/java/l-jsvr/index.shtml

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.