Base class to build multithreaded servers easily
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class MTServerBase extends Thread {
protected Socket socket;
public void run() {
try {
String s = "Server.";
socket.getOutputStream().write(s.getBytes());
socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
static public void startServer(int port, Class clobj) {
ServerSocket ssock;
Socket sock;
try {
ssock = new ServerSocket(port);
while (true) {
Socket esock = null;
try {
esock = ssock.accept();
MTServerBase t = (MTServerBase) clobj.newInstance();
t.socket = esock;
t.start();
} catch (Exception e) {
try {
esock.close();
} catch (Exception ec) {
}
}
}
} catch (IOException e) {
}
}
}
public class UCServer extends MTServerBase {
public void run() {
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
while (true) {
char c = (char) is.read();
// end on Control+C or Control+D
if (c == '\003' || c == '\004')
break;
os.write(Character.toUpperCase(c));
}
socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
System.out.println("Starting server on port " + n);
startServer(n, UCServer.class);
}
}
Related examples in the same category