Reading and Writing to a Socket for Echo

The echo protocol simply echoes back anything its sent. The following echo client reads data from an input stream, then passes it out to an output stream connected to a socket, connected to a network echo server. A second thread reads the input coming back from the server. The main() method reads some file names from the command line and passes them into the output stream.

import java.net.*;
import java.io.*;
import java.util.*;


public class Echo {

  InetAddress server;
  int port = 7;
  InputStream theInput;

  public static void main(String[] args) {

    if (args.length == 0) {
      System.err.println("Usage: java Echo file1 file2...");
      System.exit(1);
    }

    Vector v = new Vector();
    for (int i = 0; i < args.length; i++) {
      try {
        FileInputStream fis = new FileInputStream(args[i]);
        v.addElement(fis);
      }
      catch (IOException ex) {
      }
    }

    InputStream in = new SequenceInputStream(v.elements());

    try {
      Echo d = new Echo("metalab.unc.edu", in);
      d.start();
    }
    catch (IOException ex) {
      System.err.println(ex);
    }

  }

  public Echo() throws UnknownHostException {
    this (InetAddress.getLocalHost(), System.in); 
  }

  public Echo(String name) throws UnknownHostException {
    this(InetAddress.getByName(name), System.in);
  }

  public Echo(String name, InputStream is) throws UnknownHostException {
    this(InetAddress.getByName(name), is);
  }

  public Echo(InetAddress server) {
    this(server, System.in);
  }

  public Echo(InetAddress server, InputStream is) {
    this.server = server;
    theInput = is;
  }

  public void start() {
    try {
      Socket s = new Socket(server, port);
      CopyThread toServer = new CopyThread("toServer", 
       theInput, s.getOutputStream());
      CopyThread fromServer = new CopyThread("fromServer", 
       s.getInputStream(), System.out);
      toServer.start();
      fromServer.start();
    }
    catch (IOException ex) {
      System.err.println(ex);
    }
  }

}

class CopyThread extends Thread {

  InputStream in;
  OutputStream out;

  public CopyThread(String name, InputStream in, OutputStream out) {
    super(name);
    this.in = in;
    this.out = out;
  }

  public void run() {
    byte[] b = new byte[128];
    try {
      while (true) {
        int m = in.read(b, 0, b.length);
        if (m == -1) {
          System.out.println(getName() + " done!");
          break;
        }
        out.write(b, 0, m);
      }
    }
    catch (IOException ex) {
    }
  }

}


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified May 6, 2003