FileDocCategorySizeDatePackage
EchoServer.javaAPI DocExample1573Mon Oct 16 19:44:04 BST 2000None

EchoServer.java

// File: EchoServer.java
// T Balls : Oct 1999

// Create a "server" program that echoes data
// received on a TCP/IP socket to the console
// and back to the client

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


public class EchoServer
{  public static void main( String[] args )
   {  new EchoServer( 44444 ).run();
   }
   
   public EchoServer( int port )
   {  this.port = port;
   }

   private int port;
   private ServerSocket sSock;
   private Socket sock;
   private InputStream ins;
   private OutputStream outs;
   
   public void run()
   {  try
      {  sSock = new ServerSocket( port );
      }
      catch( IOException ioe )
      {  System.out.println( "Couldn't listen on port " + port );
         System.exit( -1 );
      }
      try
      {  sock = sSock.accept();
      }
      catch( IOException ioe )
      {  System.out.println( "Accept failed" );
         System.exit( -1 );
      }
      try
      {  ins = sock.getInputStream();
         outs = sock.getOutputStream();
      }
      catch( IOException ioe )
      {  System.out.println( "Failed to get I/O streams" );
         System.exit( -1 );
      }

      try
      {  int inChar = ins.read();
         while( inChar != -1 )
         {  outs.write( inChar );
            outs.flush();
            System.out.print( (char)inChar );
            inChar = ins.read();
         }
         sock.close();
      }
      catch( IOException ioe )
      {  System.out.println( "Read/write failed" );
         System.exit( -1 );
      }
   }
}