Defining a Network Connection to a Server - Java Network

Java examples for Network:ServerSocket

Description

Defining a Network Connection to a Server

Demo Code

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

public class Main {
  public static void main(String a[]) throws Exception {
    final int httpd = 1234;
    ServerSocket ssock = null;//w  w  w  .ja va 2  s  .  c  om

    ssock = new ServerSocket(httpd);
    System.out.println("have opened port 1234 locally");

    Socket sock = ssock.accept();
    System.out.println("client has made socket connection");
    communicateWithClient(sock);
    System.out.println("closing socket");
    ssock.close();
  }

  public static void communicateWithClient(Socket socket) throws Exception {
    BufferedReader in = null;
    PrintWriter out = null;
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(), true);
    String s = null;
    out.println("Server received communication!");
    while ((s = in.readLine()) != null) {
      System.out.println("received from client: " + s);
      out.flush();
      break;
    }
    in.close();
    out.close();
  }
}

Result


Related Tutorials