java.net.Socket : Socket « Network « Java Tutorial






  1. A socket is an endpoint of a network connection.
  2. A socket enables an application to read from and write to the network.
  3. The Socket class represents a "client" socket.

A simple HTTP client

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

public class MainClass {
  public static void main(String[] args) {
    String host = "www.google.com";
    String protocol = "http";
    try {
      Socket socket = new Socket(protocol + "://" + host, 80);
      OutputStream os = socket.getOutputStream();
      boolean autoflush = true;
      PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
      BufferedReader in = new BufferedReader(

      new InputStreamReader(socket.getInputStream()));

      // send an HTTP request to the web server
      out.println("GET / HTTP/1.1");
      out.println("Host: " + host + ":80");
      out.println("Connection: Close");
      out.println();

      // read the response
      boolean loop = true;
      StringBuilder sb = new StringBuilder(8096);
      while (loop) {
        if (in.ready()) {
          int i = 0;
          while (i != -1) {
            i = in.read();
            sb.append((char) i);
          }
          loop = false;
        }
      }

      // display the response to the out console
      System.out.println(sb.toString());
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}








19.9.Socket
19.9.1.java.net.Socket
19.9.2.Create a socket
19.9.3.Create Socket by IP address and port number
19.9.4.Display Socket InetAddress, Port, LocalPort and Local address
19.9.5.Socket Info
19.9.6.Get InputStream and OutputStream from Socket
19.9.7.Read float number from a Socket
19.9.8.Read Object from Socket
19.9.9.A Thin SMTP Client
19.9.10.Get internet address from connected socket client
19.9.11.Transfer a file via Socket
19.9.12.Cipher Socket