import java.net.*;
import java.io.*;
public class TestServer {
// We do no nice exception handling! Very bad!!!
// But the idea is to have a very short code.
public static void main(String[] args) throws Exception{
// We are listening to port 4321
ServerSocket server = new ServerSocket(4321);
while(true){
Socket connection = server.accept();
ConnectionHandler connectionHandler = new ConnectionHandler(connection);
new Thread(connectionHandler).start();
}
}
}
class ConnectionHandler implements Runnable{
private Socket connection;
private static int bufsize = 512;
ConnectionHandler(Socket connection){
this.connection = connection;
}
public void run(){
try{
InputStream ins = connection.getInputStream();
OutputStream outs = connection.getOutputStream();
// We will read one byte at a time.
byte[] buffer = new byte[bufsize];
try {
do {
int bytesread = ins.read(buffer);
if (bytesread == -1){
// We have the end of the input stream.
// So the other side is done. We can
// close the connection safely
break;
}
String str = new String(buffer, 0, bytesread);
System.out.print(str);
outs.write(buffer,0,bytesread);
} while (true);
} finally {
connection.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}