Listening for Connections on the Server - Java Network

Java examples for Network:Socket

Description

Listening for Connections on the Server

Demo Code

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

public class Main {
  static Socket socket = null;
  static PrintWriter out;
  static BufferedReader in;

  public static void main(String[] args) {
    try {/*from www.ja  v  a  2s. co  m*/
      socket = new Socket("127.0.0.1", 1234);
      // Obtain a handle on the socket output
      out = new PrintWriter(socket.getOutputStream(), true);
      // Obtain a handle on the socket input
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      testConnection();
      System.out.println("Closing the connection...");
      out.close();
      in.close();
      socket.close();
      System.exit(1);
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
    }
  }

  public static void testConnection() {
    String serverResponse = null;
    if (socket != null && in != null && out != null) {
      System.out.println("Successfully connected, now testing...");

      try {
        // Send data to server
        out.println("Here is a test.");
        // Receive data from server
        while ((serverResponse = in.readLine()) != null)
          System.out.println(serverResponse);
      } catch (IOException e) {
        System.out.println(e);
        System.exit(1);
      }
    }
  }
}

Result


Related Tutorials