Implementing multithreaded server programs with Java Xu Shiyun Abstract: Before Java appears, writing multithreaded programs is a cumbersome and accompanied by many unsafe factors. With Java, writing a safe and efficient multi-thread program makes simple, and we can easily implement multi-threaded server programs with multi-threaded and Java network packages. Java is generated by the tide of the Internet, has intrinsic support for network and multi-thread, with all characteristics of the programming language of the network era. From the current application of Java, Java is mainly used in Internet or LAN's network programming, and the trend of Java as a mainstream network programming language is getting more and more obvious. In actual work, in addition to using commercial server software, we often need to write your own server software in accordance with the actual environment to complete specific tasks or interact with specific client software. When implementing a server program, in order to improve program running efficiency, reduce user waiting time, we apply multi-threaded technology in Java Applet. 1. Server programs in Java and multithreading prior to Java, no mainstream programming languages provide inherent support for advanced network programming. In other language environments, realizing network programs often requires in-depth dependence on the network API of the operation platform, while Java provides a full-package-related complete software package supported by the network, so that the programmer does not need to support the system network Detail is annoyed. The network protocol in the Java package is TCP / IP is also the most popular WAN / LAN protocol today. Java's class and interface definitions in the Java.net package. Client software typically uses the core class socket in the java.net package to establish a connection with a port of the server, and the server program is different from the client, it needs to initialize a port to monitor, encounter a connection call, with the corresponding client establish connection. The ServerSocket class of the Java.NET package contains everything you need to write the server system. The partial definition of the ServerSocket class will be 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 oException;} ServerSocket constructor is the basis for server programs running, which initializes the port specified by the parameter port as the port of the server, listening to the client connection request. The range of Port is 0 to 65536, but 0 to 1023 are the standard Internet protocol reserved port, and on the UNIX host, only root users can use. A generally custom port number between 8000 and 16000. Only the serversocket is still not enough, it does not have a socket with the client interact (Socket), so you need to call the Accept method of this class to accept the customer call. The accept () method returns an instance of the communication socket until a connection request is returned. Through the input, output stream, the server can receive user instructions and respond to the client accordingly. The GetinetAddress and getLocalPort methods of the Serversocket class can get the IP address and port of the server.
The setsotimeout and getsotimeout methods are settings and getting the server timeout setting, and if the server has not received the socket instance returned by the ACCEPT method in the Timout setting time, throw an exception of IOEXCeption. Java's multi-threaded is one of the essences of Java programming, which is used to greatly improve the response time of the program and improve the parallelism of the program. In the server program, since the request or commands of different clients are often received, a command processing thread can be generated for each client, and the instructions of each user will react. In some more complicated systems, we can also generate separate threads for each database query instruction, and operate with the database. Practice has proved that the multi-threaded design can improve the response of the system and ensure the independence of the user directive. Since Java itself is "thread security", there is a programming principle to operate a new thread that can be independently completed in a thread. There are two ways to implement threads in Java, one is a subclass of the Thread class, and define the subclass's RUN method, and the operation of the thread is implemented in the method RUN. However, our defined classes are generally other class subclasses, while Java does not allow multiple inheritance, so the second method of implementing threads is to implement Runnable interfaces. The function of this thread is implemented by overlying the Run method in the Runnable interface. This example uses the first method to implement threads. Second, the multi-thread server program is an example below is the architecture of the multi-threaded server program we used in the project, which can be expanded on this basis. This example does not involve the database. If you need to update your database according to user instructions in thread operation, you should pay attention to the synchronization problem between the thread, so that the same update method can only be called by one thread at a time. Here we have two classes, ReceiveServer contains launch code ()), and initializes the instance of ServerSocket, and after the Accept method returns the user request, the returned socket will be given to the generated thread class ServerThread instance, Until the user ends the connection.
// i 类 * * a. u f p p / p f / p / p / p p 构 p 构 p 构 p () {ServerSocket rServer = null; // ServerSocket examples socket request = null; // user request 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:" received_port) WHILE (TRUE) {// Waiting for the user request request = RSERVER.ACCEPT (); // Receive the client connection request received (); // Generate serverThread instance receivethread.start (); // Start ServerThRead Thread}}} catch (ieException e) {system.out.println (E.GetMessage ());}} public static void main (String args []) {new receiveserver ();} // end of main} // end Of class // class serverThreadImport java.io. *; import java.net. *; Class ServerThread Extends thread {socket clientRequest; // User connection Communication socket bufferedReader input; // input stream PrintWriter Out PUT; // Output Flow PUBLIC ServerThread (Socket S) {// ServerThread constructor this.clientRequest = S; // Receive the socket of ReceRVER INPUTSTREADER Reader; OutputStreamWriter Writer; Try {// Initialization input, output flow 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? "