Java network server programming

xiaoxiao2021-03-06  81

Java's Socket API provides a very convenient object interface for network programming. This article uses a simple TCP Echo Server to give examples how to complete a web server using Java.

TCP Echo Server used as an example is working as follows:

When a client is connected to the server via TCP, the client can send data to the server through this connection, and the server receives the data back to the client with the same TCP connection after receiving the data. The service will keep this connection until the client is turned off.

Because the server needs to handle multiple clients at the same time, we first use a common multi-threaded service model:

Let a Thread are responsible for listening to the service port. When there is a new connection, this monitored Thread will create a new THREAD to this connection to handle it. In this way, the server can accept multiple connections and make multiple threads to process them separately.

The following is the corresponding server program:

Public class echoserver imports runnable {

Public void run () {

Try {

Serversocket SVR = New Serversocket (7);

While (true) {

Socket Sock = SVR.Accept ();

New Thread (New Echosesis (Sock). start ();

}

} catch (ioException ex) {

Throw new ExceptionAdapter (ex);

}

}

}

This code first creates a ServerSocket object and allows it to listen to the TCP port 7 and then use the Accept () method in a loop to receive a new connection and create the Thread that handles this connection. The logical that actually handles each client connection is included in the ECHOSSITION.

This class is used in the above code, and its role is to pack a checked exception into runtimeException. Detailed instructions can be made to avoid using the Checked Exception article in Java.

The following is the code of the ECHOSession:

Public class echoseession item runnable {

Public Echosesis (socket s) {

_sock = s;

}

Public void run () {

Try {

Try {

InputStream INPUT = _Sock.getInputStream ();

OutputStream output = _sock.getOutputStream ();

BYTE [] BUF = New byte [128];

While (true) {

INT count = INPUT.READ (BUF);

IF (count == -1)

Break;

Output.write (buf, 0, count);

}

} finally {

_sock.close ();

}

} catch (ioException ex) {

Throw new ExceptionAdapter (ex);

}

}

protected socket _sock = null;

}

Echosession accepts a socket object as a constructor, in its Run () method, it does not stop reading data from this socket object in InputStream and writes back to the OutputStream of the socket until this connection is closed by the client ( InputStream's Read method returns -1).

Echosession requires a thread to execute, which is easy to think of Thread as the parent class as an ECHOSession. However, this is not flexible enough, the overhead is also relatively large. And choose how much the echosession implementation runnable interface is much flexible. This can be seen in the next echo server using Thread Pool. The above is already a complete TCP Echo Server, but with the client keeps connected and disconnected, this server will constantly generate and eliminate threads, and these two are more still 'expensive' operations. In order to avoid this consumption, it can be considered using Thread pool mechanism.

Using the implementation of Thread pool in a simple Thread buffer pool, you can make the following modifications to Echoserver (Echosession does not need to make changes):

Public class echoserver imports runnable {

Public void run () {

Try {

Serversocket SVR = New Serversocket (7);

// Initialize Thread pool

Syncqueue queue = new syncqueue (10);

For (int i = 0; i <10; i ) {

New Thread (New Worker (Queue). start ();

}

While (true) {

Socket Sock = SVR.Accept ();

// put the task in Thread pool

Queue.Put (New Echosession (SOCK);

}

} catch (ioException ex) {

Throw new ExceptionAdapter (ex);

}

}

}

Here you can see the flexibility of making the Echosession implementation, you can use it in Thread pool without modifying it.

The Thread pool used in this example is relatively simple, no dynamically adjusting the number of THREAD, so this Echo Server can only serve 10 clients at the same time. However, by overloading SyncQueue, we can easily join this feature to break through this limit.

When the performance of the web server and the consensus request are high, let each client processed by a special THREAD may not meet our requirements (imagine that there are thousands of clients at the same time). At this time, you can consider using Java's NIO API to build a server architecture, because the IO operation in NIO is non-blocking, and we only need little Thread to fully utilize the CPU to process a number of clients. About NIO topics, there will be no more detailed details in this article. I hope to discuss it later. :)

Author: DaiJiaLin

Mailto: WoodyDai@gmail.com

http://blog.9cbs.net/daijiang

转载请注明原文地址:https://www.9cbs.com/read-93846.html

New Post(0)