Skip to content

Interacting with a Client

March 7, 2013
A server needs to both read a client request and write a response. The following program reads whatever the client sends and then sends it back to the client. In short this is an echo server.
import java.net.*;
import java.io.*;

public class EchoServer {
public final static int defaultPort = 2346;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
}
if (port <= 0 || port >= 65536) port = defaultPort;
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
while (true) {
int n = is.read();
if (n == -1) break;
os.write(n);
os.flush();
}
}
catch (IOException ex) {
}
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
Here is the sample session:
% telnet utopia.poly.edu 2346
Trying 128.238.3.21...
Connected to utopia.poly.edu.
Escape character is '^]'.
test
test
credit
credit
this is a test 1 2 3 12 3
this is a test 1 2 3 12 3
^]
telnet> close
Connection closed.
%

Leave a Comment

Leave a comment