ServerSocket: readUTF() and writeUTF(String str) : ServerSocket « java.net « Java by API






ServerSocket: readUTF() and writeUTF(String str)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class MainClass extends Thread {
  private ServerSocket serverSocket;

  public MainClass() throws IOException {
    serverSocket = new ServerSocket(2000);
  }

  public void run() {
    try {
      Socket client = serverSocket.accept();

      DataInputStream in = new DataInputStream(client.getInputStream());
      BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
      DataOutputStream out = new DataOutputStream(client.getOutputStream());

      while (true) {
        String message = in.readUTF();
        System.out.println(message);
        System.out.print("Enter response: ");
        String response = console.readLine();

        out.writeUTF(response);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    try {
      Thread t = new MainClass();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
           
       








Related examples in the same category

1.new ServerSocket(int port)
2.ServerSocket: accept()
3.ServerSocket: bind(SocketAddress endpoint)
4.ServerSocket: getLocalPort()
5.ServerSocket: setSoTimeout(int timeout)