Use Java to implement multi-threaded server programs

Source: Internet
Author: User

 


---- Abstract: before the emergence of Java, writing multi-threaded programs was cumbersome and accompanied by many insecure factors. Using Java to write secure and efficient multi-threaded programs becomes simple, and using multi-threaded and Java Network packages, We can conveniently implement multi-threaded server programs.

---- Java is produced along with the tide of the Internet. It has internal support for networks and multithreading and has all the characteristics of programming languages in the Network Age. From the current application of Java, Java is mainly used for network programming on the Internet or LAN, and the trend of using Java as the mainstream network programming language is becoming more and more obvious. In practice, apart from commercial server software, we often need to write our own server software according to the actual environment to complete specific tasks or interact with specific client software. To improve program running efficiency and reduce user waiting time when implementing server programs, we have applied the common multithreading technology in Java Applet.

---- 1. server programs and multithreading in Java

---- Before Java, there was no mainstream programming language that could provide inherent support for advanced network programming. In other language Environments, network programs often need to rely heavily on the Network API technology of the operating platform. Java provides a complete software package without platform relevance for network support, it makes it unnecessary for programmers to worry about the details of system network support.

---- The network protocol supported by the Java software package is TCP/IP, which is also the most popular WAN/LAN protocol. Java Network classes and interfaces are defined in the java.net package. Client software usually uses the core class Socket in the java.net package to establish a connection with a port of the server. The server program is different from the client, and it needs to initialize a port for listening, when a connection call occurs, to establish a connection with the corresponding client. The ServerSocket class of the Java.net package contains everything required to write the server system. Some definitions of the ServerSocket class are given below.

Public class ServerSocket {
Public ServerSocket (int port)
Throws IOException;
Public Socket accept () throws IOException;
Public InetAddress getInetAddress ();
Public int getLocalPort ();
Public void close () throws IOException;
Public synchronized void setSoTimeout
(Int timeout) throws SocketException;
Public synchronized int
GetSoTimeout () throws IOException;
}


---- ServerSocket constructor is the basis for running the server program. It initializes the port specified by the port parameter as the port of the server and listens to client connection requests. Port ranges from 0 to 65536, but 0 to 1023 are reserved ports of the standard Internet protocol, and these ports are only available to root users on Unix hosts. Generally, the custom port number is between 8000 and 16000. It is far from enough to initialize only ServerSocket. It does not have a Socket to interact with the client. Therefore, you need to call the accept method of this class to receive the customer call. The Accept () method returns the communication Socket (Socket) instance until there is a connection request. Through the input and output streams of this instance, the server can receive user commands and respond the corresponding results to the client. The getInetAddress and getLocalPort methods of the ServerSocket class can obtain the IP address and port of the server. The setSoTimeout and getSoTimeout methods are respectively set and get the server timeout settings. If the server does not get the socket instance returned by the accept method within the time specified by timout, an IOException is thrown.
---- Java multithreading is one of the essence of Java programming. Using it properly can greatly improve the response time of the program and program concurrency. In server programs, because different clients usually need to receive simultaneous requests or commands, a command processing thread can be generated for each client's request, and the user's commands can be reflected at the same time. In some complex systems, we can also generate separate threads for each database query command to operate the database in parallel. Practice has proved that the multi-thread design can improve the system response and ensure the independence of user instruction execution. Java itself is "thread-safe", so there is a programming principle that a new thread should be opened up for operations that can be completed independently in a thread.

---- There are two ways to implement threads in Java. One is to generate a subclass of the Thread class and define its own run method. Thread operations are implemented in method run. However, the classes we define are generally subclasses of other classes, and Java does not allow multiple inheritance. Therefore, the second method to implement the thread is to implement the Runnable interface. Override the run method in the Runnable interface to implement the function of this thread. This example uses the first method to implement the thread.

---- Example of a multi-thread server program

---- The following is the architecture of the multi-threaded server program we use in the project. We can expand the commands on this basis. This example does not involve databases. If the database needs to be updated according to user instructions during thread running, pay attention to the synchronization problem between threads so that the same update method can only be called by one thread at a time. Here we have two classes. The javaseserver contains the startup code (main () and initializes the ServerSocket instance. After the accept method returns the user request, it returns the Socket) the instance is handed over to the generated thread-type serverThread until the user ends the connection.

// Class exploreserver
Import java. io .*;
Import java. util .*;
Import java.net .*;

Public class receiveServer {

Final int RECEIVE_PORT = 9090;
// The port number of the server

// Constructor of javaseserver
Public exploreserver (){
ServerSocket rServer = null;
// ServerSocket instance
Socket request = null; // user requested Socket
Thread receiveThread = null;
Try {
RServer = new ServerSocket (RECEIVE_PORT );
// Initialize ServerSocket
System. out. println ("Welcome to the server! ");
System. out. println (new Date ());
System. out. println ("The server is ready! ");
System. out. println ("Port:" + RECEIVE_PORT );
While (true) {// wait for user request
Request = rServer. accept ();
// Receives client connection requests
ReceiveThread = new serverThread (request );
// Generate the serverThread instance
Deleethread. start ();
// Start the serverThread
}
} Catch (IOException e ){
System. out. println (e. getMessage ());}
}

Public static void main (String args []) {
New exploreserver ();
} // End of main

} // End of class

// Class serverThread
Import java. io .*;
Import java.net .*;

Class serverThread extends Thread {

Socket clientRequest;
// User-connected communication socket
BufferedReader input; // input stream
PrintWriter output; // output stream

Public serverThread (Socket s)
{// ServerThread Constructor
This. clientRequest = s;
// Receives sockets from the javaseserver.
InputStreamReader reader;
OutputStreamWriter writer;
Try {// initialize the input and output streams
Reader = new InputStreamReader
(ClientRequest. getInputStream ());
Writer = new OutputStreamWriter
(ClientRequest. getOutputStream ());
Input = new BufferedReader (reader );
Output = new PrintWriter (writer, true );
} Catch (IOException e ){
System. out. println (e. getMessage ());}
Output. println ("Welcome to the server! ");
// Client connection welcome word
Output. println ("Now is:
"+ New java. util. Date () +" "+
"Port:" + clientRequest. getLocalPort ());
Output. println ("What can I do for you? ");
}
Public void run () {// thread execution Method
String command = null; // USER command
String str = null;
Boolean done = false;

While (! Done ){
Try {
Str = input. readLine (); // receives client commands
} Catch (IOException e ){
System. out. println (e. getMessage ());}
Command = str. trim (). toUpperCase ();
If (str = null | command. equals ("QUIT "))
// Command quit to end the connection
Done = true;
Else if (command. equals ("HELP ")){
// Command help to query commands acceptable to the server
Output. println ("query ");
Output. println ("quit ");
Output. println ("help ");
}
Else if (command. startsWith ("QUERY "))
{// Command query
Output. println ("OK to query something! ");
}
// Else if ........ // Other commands that can be added to the server
Else if (! Command. startsWith ("HELP ")&&
! Command. startsWith ("QUIT ")&&
! Command. startsWith ("QUERY ")){
Output. println ("Command not Found!
Please refer to the HELP! ");
}
} // End of while
Try {
ClientRequest. close (); // close the socket
} Catch (IOException e ){
System. out. println (e. getMessage ());
}
Command = null;
} // End of run

---- After the server program is started, you can use the telnet machine port command to connect. machine is the local name or address, and port is the port specified in the program. You can also write specific client software to establish a connection through TCP Socket.

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.