Before Java appears, writing multithreaded programs is a cumbersome and with many unsafe factors.
Best. Using Java, writing a safe and efficient multi-thread program is simple, and multithreaded and JA
VA's network package we can easily implement multithreaded server programs.
---- Java is generated by the tide of the Internet, has intrinsic support for the network and multi-thread, with
All characteristics of all programming languages. From Java's current application, Java is mainly used in Internet
Or the network programming on the LAN, and the trend of Java as a mainstream network programming language is getting more and more
. In actual work, in addition to using commercial server software, we often need to compile according to the actual environment.
Write your own server software to complete specific tasks or interact with specific client software. In realization
In order to improve program operation efficiency, we apply in Java App to improve program operation efficiency, reduce user waiting time.
Multi-threading technology in Letters.
---- First, server programs and multi-threads in Java
---- No mainstream programming language can provide inherent support for advanced network programming before Java.
In other language environments, realizing network programs often requires deep-depth technology of network APIs on operating platforms.
Going, and Java provides a full-software package supported by the network, so that the programmer does not have to
To worry about the details of the system network support.
---- The network protocol in the Java package is TCP / IP, which is also the most popular WAN / LAN in today.
Web protocol. Java's class and interface definitions in the Java.net package. Client software usually uses JA
The core class socket in the VA.NET package establishes a connection to a port of the server, and the server program is different from
Client, it needs to initialize a port for monitoring, encounter connection calls, and build corresponding customers
Connection. The ServerSocket class of the Java.NET package contains everything you need to write the server system. the following
Give some part definitions for the ServerSocket class.
Public class serversocket {
Public Serversocket (INT Port)
Throws oException;
Public socket accept () throws oException;
Public inetaddress getinetaddress ();
Public int getLocalPort ();
Public void close () throws oException;
Public synchronized void setsotimeout
INT TIMEOUT "
Public Synchronized Int
Getsotimeout () throws oException;
}
---- Serversocket constructor is the basis of the server program running, it will set the port specified by the parameter port
Improve the port as the server listener client connection request. The range of Port is 0 to 65536, but 0 to
1023 is a standard Internet protocol to retain port, and on UNIX hosts, only root users
can use. A generally custom port number between 8000 and 16000. Serversocket is only initialized
It's not enough, it doesn't have a socket that interacts with the client, so you need to call this class.
The Accept method accepts a customer call. Accept () method Returns the communication socket until a connection request is returned (SOC
Example of KET). Through the input, output stream, the server can receive user instructions and will
The client should respond to the client. The GetinetAddress and getLocalPort methods of the Serversocket class can get the IP address and port of the server. Setsotimeout and getSotimeout methods are setup and get
To the server timeout setting, if the server has not received the Accept method in Timout setting time
Socket instance, throw an exception of IOEXCEPTION.
---- Java multi-threaded can be described as one of the essences of Java programming, which is used to greatly improve procedures.
The response time, improve the parallelism of the program. In server programs, due to often receive different clients
At the same time request or command, you can generate a command processing thread for each client's request,
The instructions of each user have responded. In some more complicated systems, we can also query each database
The instruction generates a separate thread and operates the database. Practice proves that multi-threaded design can be used
Very good improvement system response and guarantees the independence of the user directive. Because Java itself is "thread safety
All, therefore, there is a programming principle to operate independently in a thread.
New thread.
---- There are two ways to implement thread in Java, one is the subclass of the Thread class, and define the subclass
The RUN method, the operation of the thread is implemented in the method RUN. But our definition class is generally other classes
Class, while Java does not allow multiple inheritance, so the second method of implementing thread is to implement Runnable interface
. The function of this thread is implemented by overlying the Run method in the Runnable interface. This example uses the first part
Law implementation thread.
---- II, multithreaded server program example
---- The following is the architecture of the multi-threaded server program we used in the project, you can live on this basis.
Extension. This example does not involve the database. If you need a database according to user instructions in thread operation
Update, you should pay attention to the synchronization problem between the thread, so that the same update method can only be one line at a time.
Cast. Here we have two classes, ReceiveServer contains launch code (main ()) and initializes
SERVERSCKET's instance, after the Accept method returns a user request, the socket will be returned (Socket)
) The instance of the generated thread class ServerThread until the user ends the connection.
// Class ReceiveServer
Import java.io. *;
Import java.util. *;
Import java.net. *;
Public class receiveserver {
Final int received_port = 9090;
/ / The port number of the server
// ReceiveServer constructor
Public receiveserver () {
Serversocket Rserver = NULL;
// serversocket instance
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:" receive_port);
While (true) {// Waiting for user request
REQUEST = RSERVER.ACCEPT ();
// Receive client connection request receivethread = new serverthread (request);
/ / Generate instances of ServerThread
Receivethread.start ();
// Start the ServerThread thread
}
} catch (ioexception e) {
System.out.println (E.getMessage ());
}
Public static void main (string args []) {
New receiveserver ();
} // end of main
} // End of class
// class ServerThread
Import java.io. *;
Import java.net. *;
Class ServerThread Extends Thread {
Socket ClientRequest;
/ / User connection communication socket
BufferedReader INPUT; / / Enter flow
PrintWriter Output; // Output stream
Public ServerThread (Socket S)
{// serverThread constructor
This.clientRequest = S;
/ / Receive the socket from ReceiveServer
InputStreamReader 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
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 instruction
String str = NULL;
Boolean done = false;
While (! done) {
Try {
Str = INPUT.Readline (); // Receive client instructions
} catch (ioexception e) {
System.out.println (E.getMessage ());
Command = str.trim (). Touppercase ();
IF (str == null || comMmand.equals ("quit"))
// Command quit end this connection
DONE = true;
Else IF (Command.equals ("Help")) {
/ / Command HELP Query this server acceptable command
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 instructions to join the server here
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 starting the server program, you can use the Telnet machine port command, where Machine is
This name or address, Port is the port specified in the program. You can also write a specific client software through TC
P Socket socket establishes a connection.