Use Java to implement multi-thread serversocket server programs

Source: Internet
Author: User

Java is produced along with the tide of the Internet. It has internal support for networks and multithreading and has all the features of programming languages in the Network Age. From the current Java application, Java
It 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
In addition, you often need to write your 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
We have applied the multithreading technology that is common in Java applet.

I. server programs and multithreading in Java

Before Java, no mainstream programming language 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.
Connect to a connection call to establish a connection with the corresponding client. The serversocket class of the java.net package contains everything required to write the server system. Below
Some definitions of the serversocket class.

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 ;

The serversocket constructor is the basis for running the program on the server. It initializes the port specified by the port parameter as the port of the server and listens to client connection requests. Port fan
The range is 0 to 65536, but 0 to 1023 is the standard Internet Protocol reserved port, and on UNIX hosts, these ports are only available to the root user. General custom port number
Between 8000 and 16000. It is not enough to initialize serversocket only. It does not have a socket for interaction with the client. Therefore, you need to call
The accept method accepts customer calls. The accept () method returns the communication socket (socket) instance until there is a connection request. The server can connect
Receive user instructions and respond to the client. The getinetaddress and getlocalport methods of the serversocket class can obtain the IP address of the server.
Address and port. The setsotimeout and getsotimeout methods are respectively set and get the server timeout settings.
The socket instance returned by the accept method throws an ioexception.

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, different customers are often accepted.
User requests or commands at the same time. Therefore, you can generate a command processing thread for each client request and respond to the user's commands at the same time. In some complex systems, we can also query
The query command generates a separate thread 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. Because Java itself is a "line
Program security, so there is a programming principle that operations that can be completed independently in a thread should open up a new 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, we define Class 1
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
The function of this thread. This example uses the first method to implement the thread.

Ii. Examples of multi-thread server programs

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 you need to import
For row update operations, pay attention to the synchronization 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 initialize the serversocket instance. After the accept method returns the user request, the returned socket (socket) is handed over to the generated Thread class.
Server thread instance 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 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.