Echo Echo Echo… 19.02.
This blog item has no other purpose than terrifying Lauren, as she will be switching to doing computer stuff in uni soon…just like me. She is now officially doomed. Here is my latest homework assignment, a multithreaded binary echo server using java (it doesn`t look very fancy because WP doesn`t indent):
MultiEchoServer.java
import java.net.*;import java.io.*;public class MultiEchoServer{ServerSocket socket;public MultiEchoServer(){//Try to open a sockettry{socket = new ServerSocket(1337);}//Close the program if it failscatch(IOException ioe){System.out.println(“Server error, program terminating…”);System.err.println(“Exception: ” + ioe);System.exit(1);}System.out.println(“Server started and listening…”);while (true){//Make a connection and start a threadtry{Socket client = socket.accept();Thread t1 = new Thread(new ClientHandler(client));t1.start();}//error handlingcatch (IOException ioe){System.err.println(“Exception: ” + ioe);}}}public static void main (String[] args){//make the servernew MultiEchoServer();}}
import java.io.*;import java.net.*;//The class echothread is the actual thread, and is pretty much equal to the server class of the non multithreaded project.class ClientHandler implements Runnable{Socket sock;//initializing the socketpublic ClientHandler(Socket s){sock = s;}public void run(){try{//make the input and output streamInputStream input = sock.getInputStream();OutputStream output = sock.getOutputStream();while (true){//execute code while i does not equal -1do{byte b;while((b = (byte) input.read()) != -1){output.write(b);}System.out.println(“system will now be terminated..”);output.close();input.close();sock.close();}while (true);}}catch (IOException ioe){System.err.println(“Exception: ” + ioe);}}}
import java.net.*;import java.io.*;public class MultiEchoClient{public static void main(String[] args){try{//make connection to server socketSocket socket = new Socket(“127.0.0.1″, 1337);OutputStream output = socket.getOutputStream();InputStream input = socket.getInputStream();//introduction messageSystem.out.println(“Hallo!”);//execute code while i does not equal -1do{byte b;while ((b = (byte) System.in.read()) != -1){output.write(b);b = (byte) input.read();String str = “”;str += (char) b;System.out.print(str);}System.out.println(“system will now be terminated..”);output.close();input.close();socket.close();}while (true);}//Error Handlingcatch (IOException ioe){System.err.println(“Exception: ” + ioe);}}}