HelloServer
because it had only a very brief interaction with each client.
However the EchoServer
might hang on to a connection indefinitely.
In this case, it's better to make your server multi-threaded.
There should be a loop which continually accepts new connections. However, rather than handling the connection directly the Socket
should be
passed to a Thread
object that handles the connection.The following example is a threaded echo program.
import java.net.*;
import java.io.*;
public class ThreadedEchoServer extends Thread {
public final static int defaultPort = 2347;
Socket theConnection;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
}
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
ThreadedEchoServer tes = new ThreadedEchoServer(s);
tes.start();
}
catch (IOException e) {
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
public ThreadedEchoServer(Socket s) {
theConnection = s;
}
public void run() {
try {
OutputStream os = theConnection.getOutputStream();
InputStream is = theConnection.getInputStream();
while (true) {
int n = is.read();
if (n == -1) break;
os.write(n);
os.flush();
}
}
catch (IOException e) {
}
}
}
Note that explicit yields are not required because all the different threads will tend to block on calls to read()
and accept()
.