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 socket
try
{
socket = new ServerSocket(1337);
}
//Close the program if it fails
catch(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 thread
try
{
Socket client = socket.accept();
Thread t1 = new Thread(new ClientHandler(client));
t1.start();
}
//error handling
catch (IOException ioe)
{
System.err.println(“Exception: ” + ioe);
}
}
}
public static void main (String[] args)
{
//make the server
new MultiEchoServer();
}
}
ClientHandler.java
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 socket
public ClientHandler(Socket s)
{
sock = s;
}
public void run()
{
try
{
//make the input and output stream
InputStream input = sock.getInputStream();
OutputStream output = sock.getOutputStream();
while (true)
{
//execute code while i does not equal -1
do
{
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);
}
}
}
MultiEchoClient.java
import java.net.*;
import java.io.*;
public class MultiEchoClient
{
public static void main(String[] args)
{
try
{
//make connection to server socket
Socket socket = new Socket(“127.0.0.1″, 1337);
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
//introduction message
System.out.println(“Hallo!”);
//execute code while i does not equal -1
do
{
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 Handling
catch (IOException ioe)
{
System.err.println(“Exception: ” + ioe);
}
}
}
Want to know what this does? Nothing but echo back to you what you type in the console. That`s right…you need all this code to make a computer say hi back to you after you said hi to him. BE AFRAID LAUREN, BE VERY AFRAID!!!!!
-Bernadet