Example of Echo Client in Java

Socket s = new Socket("192.168.1.1", 123);   // Create socket
InputStream i = s.getInputStream();    // Get input stream
OutputStream o = s.getOutputStream();   // Get output stream
String str;
do
{
  byte[] line = new byte[100];
  System.in.read(line);                 // Read from console
  o.write(line);                        // Send the message
  i.read(line);                         // Read it back
  str = new String(line);               // Convert to string
  System.out.println(str.trim());       // Print message
}
while ( !str.trim().equals("bye") );
s.close();                 // Close connection

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.