Read from a Server with Socket - Java Network

Java examples for Network:Socket

Description

Read from a Server with Socket

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Main {
  public static void main(String[] arguments) {
    try (Socket digit = new Socket("127.0.0.1", 79);
        BufferedReader in = new BufferedReader(new InputStreamReader(
            digit.getInputStream()));) {

      digit.setSoTimeout(20000);//from w  w w  .ja v  a  2 s . c  o m
      PrintStream out = new PrintStream(digit.getOutputStream());
      out.print("\015\012");

      boolean eof = false;
      while (!eof) {
        String line = in.readLine();
        if (line != null) {
          System.out.println(line);
        } else {
          eof = true;
        }
      }
      digit.close();
    } catch (IOException e) {
      System.out.println("IO Error:" + e.getMessage());
    }
  }
}

Result


Related Tutorials