Question: EchoServer.java: /** * An echo server listening on port 6007. This server reads from the client * and echoes back the result. When the client

 EchoServer.java: /** * An echo server listening on port 6007. This

EchoServer.java:

/**

* An echo server listening on port 6007. This server reads from the client

* and echoes back the result. When the client enters the character '.' - the

* server closes the connection.

*/

import java.net.*;

import java.io.*;

import java.sql.Connection;

public class EchoServer

{

public static final int DEFAULT_PORT = 6007;

public static void main(String[] args) throws IOException {

ServerSocket sock = null;

try {

// establish the socket

sock = new ServerSocket(DEFAULT_PORT);

while (true) {

/**

* now listen for connections

* and service the connection in a separate thread.

*/

Thread worker = new Thread(new Connection(sock.accept()));

worker.start();

}

}

catch (IOException ioe) { }

finally {

if (sock != null)

sock.close();

}

}

}

Connection.java:

/**

* This is the separate thread that services each

* incoming echo client request.

*/

import java.net.*;

import java.io.*;

public class Connection implements Runnable

{

private Socket client;

private Handler handler = new Handler();

public Connection(Socket client) {

this.client = client;

}

public void run() {

try {

handler.process(client);

}

catch (IOException e) {

e.printStackTrace();

}

}

}

Handler.java:

/**

* Handler class containing the logic for echoing results back

* to the client.

*/

import java.io.*;

import java.net.*;

public class Handler

{

public static final int BUFFER_SIZE = 256;

/**

* this method is invoked by a separate thread

*/

public void process(Socket client) throws IOException {

byte[] buffer = new byte[BUFFER_SIZE];

String line;

InputStream fromClient = null;

OutputStream toClient = null;

try {

/**

* get the input and output streams associated with the socket.

*/

fromClient = new BufferedInputStream(client.getInputStream());

toClient = new BufferedOutputStream(client.getOutputStream());

int numBytes;

/** continually loop until the client closes the connection */

while ( (numBytes = fromClient.read(buffer)) != -1) {

toClient.write(buffer, 0, numBytes);

toClient.flush();

}

}

catch (IOException ioe) {

System.err.println(ioe);

}

finally {

// close streams and socket

if (fromClient != null)

fromClient.close();

if (toClient != null)

toClient.close();

if (client != null)

client.close();

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!