Java Reference
In-Depth Information
21
EchoProtocol protocol = new EchoProtocol(clntSock, logger);
22
Thread thread = new Thread(protocol);
23
thread.start();
24
logger.writeEntry("Created and started Thread="+thread.getName());
25
} catch (IOException e) {
26
logger.writeEntry("Exception="+e.getMessage());
27
}
28
}
29
/* NOT REACHED */
30
}
31
}
TCPEchoServerThread.java
1.
Parameter parsing and server socket/logger creation:
lines 7-15
2.
Loop forever, handling incoming connections:
lines 17-28
Accept an incoming connection:
line 20
Create a protocol instance to handle new connection:
line 21
Each connection gets its own instance of
EchoProtocol
. Each instance maintains the
state of its particular connection. The echo protocol has little internal state, but more
sophisticated protocols may require substantial amounts of state.
Create, start, and log a new thread for the connection:
lines 22-24
Since
EchoProtocol
implements the
Runnable
interface, we can give our new instance
to the
Thread
constructor, and the new thread will execute the
run()
method of
EchoProtocol
when
start()
is invoked. The
getName()
method of
Thread
returns a
String
containing a name for the new thread.
Handle exception from
accept()
:
lines 25-27
If some I/O error occurs,
accept()
throws an
IOException
. In our earlier iterative echo
server (
TCPEchoServer.java
), the exception is not handled, and such an error terminates
the server. Here we handle the exception by logging the error and continuing execution.
4.1.4 Factoring the Server
Our threaded server does what we want it to, but the code is not very reusable or extensible.
First, the echo protocol is hard-coded in the server. What if we want an HTTP server instead? We
could write an
HTTPProtocol
and replace the instantiation of
EchoProtocol
in
main()
; however,
we would have to revise
main()
and have a separate main class for each different protocol that
we implement.
We want to be able to instantiate a protocol instance of the appropriate type for each
connection without knowing any specifics about the protocol, including the name of a con-
structor. This problem—instantiating an object without knowing details about its type—arises
frequently in object-oriented programming, and there is a standard solution: use a
factory
.A
Search WWH ::
Custom Search