An Echo Client Based on TCP Sockets - Java Network

Java examples for Network:TCP

Description

An Echo Client Based on TCP Sockets

Demo Code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class Main {
  public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 12900);
    System.out.println("Started client socket at "
        + socket.getLocalSocketAddress());

    BufferedReader socketReader = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));// ww  w  .  j  av a2s.  co  m
    BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(
        socket.getOutputStream()));

    BufferedReader consoleReader = new BufferedReader(new InputStreamReader(
        System.in));

    String promptMsg = "Please enter a message (Bye to quit):";
    String outMsg = null;

    System.out.print(promptMsg);
    while ((outMsg = consoleReader.readLine()) != null) {
      if (outMsg.equalsIgnoreCase("bye")) {
        break;
      }
      socketWriter.write(outMsg);
      socketWriter.write("\n");
      socketWriter.flush();

      String inMsg = socketReader.readLine();
      System.out.println("Server: " + inMsg);

      System.out.println(); // Print a blank line
      System.out.print(promptMsg);
    }
    socket.close();
  }
}

Related Tutorials