Example of echo server in Java

try
{
  ServerSocket s = new ServerSocket(1234);  // Create server
  while (true)
  {
   Socket c = s.accept();        // Await connection
   InputStream i = c.getInputStream(); // Get input stream
   OutputStream o = c.getOutputStream();//Get output stream
   do
   {
     byte[] line = new byte[100];   // Create scratchpad
     i.read(line);        // Read client's message
     o.write(line);            // Send it back
   }
   while ( !str.trim().equals("eof") );
   c.close();              // Close connection
  }
}
catch (Exception err)
{
  System.err.println(err);
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.