Java Network programming Question:
Download Questions PDF

If you do not want your program to halt while it waits for a connection, put the call to accept( ) in a separate thread?


If you don't want your program to halt while it waits for a connection, put the call to accept( ) in a separate thread.

When you add exception handling, the code becomes somewhat more convoluted. It's important to distinguish between exceptions thrown by the ServerSocket, which should probably shut down the server and log an error message, and exceptions thrown by a Socket, which should just close that active connection. Exceptions thrown by the accept( ) method are an intermediate case that can go either way. To do this, you'll need to nest your try blocks. Finally, most servers will want to make sure that all sockets they accept are closed when they're finished. Even if the protocol specifies that clients are responsible for closing connections, clients do not always strictly adhere to the protocol. The call to close( ) also has to be wrapped in a try block that catches an IOException. However, if you do catch an IOException when closing the socket, ignore it. It just means that the client closed the socket before the server could. Here's a slightly more realistic example:

try {
ServerSocket server = new ServerSocket(5776);
while (true) {
Socket connection = server.accept( );
try {
OutputStreamWriter out
= new OutputStreamWriter
(connection.getOutputStream( ));
out.write("You've connected to this server.
Bye-bye now.rn");
connection.close( );
catch (IOException e) {
// This tends to be a transitory error for
this one connection; e.g. the client
broke the connection early. Consequently,
// we don't want to break the loop or print
an error message. However, you might choose
to log this exception in an error log.//
// Most servers will want to guarantee
that sockets are closed
// when complete.
try {
if (connection != null) connection.close( );
catch (IOException e) {}
catch (IOException e) {

Download Java Network programming Interview Questions And Answers PDF

Previous QuestionNext Question
Public ServerSocket(int port, int queueLength) throws IOException, BindException?What is a Thread Pool?