Echo client
Most servers uses port 7 to echo the input, we will use this fact in this example. To run this example you must know the hostname of a server, if you don't, you can try a norwegian college server "svale.hia.no"
 
import java.net.Socket;
import java.io.*;
We import only the Socket class from java.net package to save compiling time, and the entire java.io package to save writing time (I'm a little lazy, we only need three classes).
public class EchoClient{

 Socket sock;
 public final int ECHO_PORT=7;
 InputStream in;
 OutputStream out;
 String line;

We declare a Socket object to use for connecting to the server, the ECHO_PORT  is final, so that it can't be changed. Input/Output Stream are declared so that we can communicate with the server. The line is just for so that the program knows what to send.
 
public EchoClient(String host){
   try{
     sock=new Socket(host,ECHO_PORT);
     in=sock.getInputStream();
     out=sock.getOutputStream();
        }
    catch(IOException ex){
      System.out.println("Error while connecting to host");
      System.out.println("Maybe you should try another host.");
      System.exit(0);
       }
   line="";
 }
This constructor takes, as an argument, the hostname. When we initializes the socket and streams, there may be thrown an IOException. This must be caught in the try/catch clause. If an exception occurs, this means that either of the objects couldn't be initialized, so we write a error message to the standard output and exits. The line is set to empty just to be something.
public void send_get(){

    int len=line.length();
    try{
       if(!(line.equals(""))){
       for(int i=0;i<len;i++)
       out.write((int)line.charAt(i));
       out.write((int)'\n');

I called this method send_get, its a silly name, but I used it because the method both sends the string and recieves the answer from the server.
The output part uses write(int) method, which thows IOException, so again we need to catch it.
First we check if the string is empty, cause there is no use in trying to write an empty string to the server. Then we ru through a for loop which have the same length as the line. To obtain the ascii int representation of each character in the string we use the String.charAt(int) method, this returns a character which is a primitive datatype. This means that all we have to do to convert it to a int is to place (int) in front of it. This is a useful trick, you can experiment with this for double, long, short etc. Try to convert them to each othe (not in this program though, that will cause a compiling error).
  line="";
  while((len=in.read())!=(char)'\n')
      line+=String.valueOf((char)len);
  System.out.print("Response from server: ");
  System.out.println(line);
   }
     }
 catch(Exception e){e.printStackTrace();}
 }
In this part of the send_get method we first erase all the data in "line", so that we can use it to save the response from the server. Then we run through the while loop, adding the response to "line" character by character, untill we encounter the int representation of linefeed(\n), we use this as a sign from the server that it is finnished sending data. Then we just print the line to the standard output, and close up.
public void execute()throws IOException{

    DataInputStream dain=new DataInputStream(System.in);
    System.out.print("Enter first word, exit to end >");
    System.out.flush();
    line=dain.readLine();

    while(!(line.equals("exit"))){
      send_get();
      System.out.print("Enter next word >");
      System.out.flush();
      line=dain.readLine();
    }

 in.close();
 out.close();
 sock.close();
 }

This method takes commands from the user, this is the method in which the program run. First we declare an object of DataInputStream, associated with the standard input stream. This will caus a warning in jdk 1.1/1.2 since this class is "deprecated" (means old, there is a new way of doing it). I don't want to use the new class (Buffered reader, you may try it out), because in my experience it doesn't work all the time. Anyway we then write the first instruction to the screen, then we use the deprecated method to read a text from the user, and put it in "line". Now we enter the while loop, every time we run through it, it tests if "line" is "exit" or not, if it isn't we go through the loop, invoke the send_get method. Then we write the next instruction and puts the input in "line" once again. Note that the readLine method blocks the program until you hit return, this is a good thing, because if the program had continued execution it would try to write to the server and it would be very messy (I tried using thread, and found out that this is the best way to do it. It was acting very strange, so I just made it this way. However Thread is another tutorial). At last we close the streams and the socket, this will only be done when the user decides to quit the program. "A good program always clean up after itself" (~Sun java tutorial), thats why we close them. A lot of these methods throws IOException, this time we just tell java that this may happen in the begining of the method and don't have to worry about it here.
   public static void main(String args[]){

 if(args.length!=1){
  System.out.println("This program takes the hostname");
  System.out.println("as the only argument.");
  System.exit(0);}

 String host=args[0];
 EchoClient ec=new EchoClient(host);
 try{
    ec.execute();
    }
 catch(IOException e){e.printStackTrace();}
 }
}

This just starts the program. An application must define the main method in the class that starts it. What is does is to create an object of its own class and call the execute method(at least here it does). We said that the execute method may throw an IOException so we didn't have to worry about it there. Now on the other hand we have to worry about it, so just invoke it in a try/catch clause. You may want to try to add "throws IOException" here too. I did it once and the entire system chrashed, it was rather annoying, but I'm not sure this was the reason. Anyway this should be safe.
Remember that this is a console application, and it runs in a command shell (ms-dos prompt, unix shell etc), and it doesn't have a fancy interface. However it shows the principles quite well. Remember to visit the sponser at the bottom of my  homepage.