Disconnected conversations between Java servers and customers, socket, and Multithreading

Source: Internet
Author: User

Use Java to implement multi-threaded server programs

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 features 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.

I. server programs and multithreading in Java before Java, no mainstream programming language can 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 ;}

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 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.

Ii. Examples of multi-threaded server programs the following is the architecture of the multi-threaded server program we use in the project. On this basis, we can expand the commands. 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 javaseserver import java. Io .*;

Import java. util .*;

Import java.net .*;

Public class receiveserver {

Final int receive_port = 9090;

// The port number of the server // The constructor of the exploreserver

Public exploreserver (){

Serversocket rserver = NULL ;/

/Serversocket instance

Socket request = NULL; // user requested socket

Thread deleethread = 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); // generates the serverthread instance.

Receivethread. Start (); // start the serverthread thread}

} 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 the socket inputstreamreader from javaseserver; outputstreamwriter writer; try {// initializes the input and output stream 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 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 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.

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.