Java Reference
In-Depth Information
17
public synchronized void writeEntry(String entry) {
18
out.println(entry);
19
out.println();
20
}
21 }
FileLogger.java
We are now ready to introduce some different approaches to concurrent servers.
4.1.3 Thread-per-Client
In a thread-per-client server, a new thread is created to handle each connection. The server
executes a loop that runs forever, listening for connections on a specified port and repeatedly
accepting an incoming connection from a client and then spawning a new thread to handle
that connection.
TCPEchoServerThread.java implements the thread-per-client architecture. It is very similar
to the iterative server, using a single indefinite loop to receive and process client requests. The
main difference is that it creates a thread to handle the connection instead of handling it
directly. (This is possible because EchoProtocol implements the Runnable interface.)
TCPEchoServerThread.java
0 import java.net.*; // for Socket, ServerSocket, and InetAddress
1 import java.io.*;
// for IOException and Input/OutputStream
2
3 public class TCPEchoServerThread {
4
5
public static void main(String[] args) throws IOException {
6
7
if (args.length != 1) // Test for correct # of args
8
throw new IllegalArgumentException("Parameter(s): <Port>");
9
10
int echoServPort = Integer.parseInt(args[0]); // Server port
11
12
// Create a server socket to accept client connection requests
13
ServerSocket servSock = new ServerSocket(echoServPort);
14
15
Logger logger = new ConsoleLogger();
// Log messages to console
16
17
// Run forever, accepting and spawning threads to service each connection
18
for (;;) {
19
try {
20
Socket clntSock = servSock.accept(); // Block waiting for connection
Search WWH ::




Custom Search