Echo Server

This program listens to a port (7 by default), it accepts one connection and stops execution after the connection is closed. It accept only one connection, if you want to learn how to accept multiple requests, take a look at the thread tutorial.

import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.*;

public class EchoServer{

     Socket sock;
     ServerSocket server;
     final int DEFAULT_PORT=7;
     InputStream in;
     OutputStream out;

in adition to the objects in the Echo client class, we create a serversocket to listen for requests. We also import the InetAddress class so we can find the host name of the computer you are running the program from (This is so we can know what host we shall connect to).
public EchoServer(int port){

     if(port==0)
         port=DEFAULT_PORT;
     try{
         server=new ServerSocket(port);
         }
     catch(IOException e){
     System.out.println("Error initializing server");}
 }

Not much new here. if the port sent to this method is 0, that means that either it is not specified, or there was an error while specifing it, so we will use the default one. The call to the ServerSocket constructor takes one argument, the port which it shall listen to. It throws IOException, so we will have to catch it.
public String getHostName()throws Exception{

    return InetAddress.getLocalHost().getHostName();}

public int getPort(){

    return server.getLocalPort();}

These two methods gets the hostname and port and return them to the place they are called from. The first one uses the InetAddress class and this method throws a MalformedURLException. This is a subclass of Exception so it is ok to catch this.
public void get_send(){

    String line="";
    int tmp=0;

    try{

    sock=server.accept();
    in=sock.getInputStream();
    out=sock.getOutputStream();

First we defines line as an empty string and the int variable tmp to 0. Then we invoke the accept method to define sock, this method blocks the program until a connection request arives, then we get the streams.
 while(true){
    line="";
    if((tmp=in.read())==-1)
        break;
    line+=String.valueOf((char)tmp);
    while((tmp=in.read())!=(int)'\n')
       line+=String.valueOf((char)tmp);
Here the program enters an infinite loop (unless the if statement, in yellow, is true). I checked up what happened if the connection was close frome the client, and the server start to read -1 integers, so we need to be aware of that. If this statement is not -1, it will block untill it recieves an input, so we will need to add it to the line when we finally get it. In the while loop we read untill we get a newline character, and add it to the line.
   line+="\n";
   tmp=line.length();
   for(int i=0;i
       out.write((int)line.charAt(i));
      }
   }
 catch(IOException e){}
Now we add newline character to the line, so the client can understand when we are finnished writing, and find the length of the String to determine the length of the loop. in the loop we write each character of the string to the output stream, so that the connected client can read it.
finally{try{
      in.close();
      out.close();
      sock.close();}
  catch(IOException e){}}
 }
When we jump out of the "infinite" while loop (that is, when the client disconnect), we must clean up. We do that here.
   public static void main(String args[]){

 int port=0;
 if(args.length ==1){
     try{
  port=Integer.parseInt(args[0]);
  }
      catch(NumberFormatException e){}
  }

 EchoServer e=new EchoServer(port);
 try{
     System.out.println(e.getHostName()+"/"+e.getPort());
     }
 catch(Exception ex){}
 e.get_send();
 }
}

If the arguments send to the program through the command line when opening it, is 1 we try to convert it from a string to an int. If this isn't possible, we just catch the numberformat exception, but does nothing (the port is 0, and we will use the default port.). Then we first initializes the server, then we try to print the hostname and port (this is where I used the superclass instead of the exception actually thrown earlier). And at last we start the get_send method.

You don't have to pass an argument to the main method. And if you use the client program described earlier in this tutorial, it doesn't make any difference, you will have to make it listen to port 7 to make the client work.
Remember to check out the sponsors at the bottom of my  homepage.