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

Home
Java Tutorial
1.Language
2.Data Type
3.Operators
4.Statement Control
5.Class Definition
6.Development
7.Reflection
8.Regular Expressions
9.Collections
10.Thread
11.File
12.Generics
13.I18N
14.Swing
15.Swing Event
16.2D Graphics
17.SWT
18.SWT 2D Graphics
19.Network
20.Database
21.Hibernate
22.JPA
23.JSP
24.JSTL
25.Servlet
26.Web Services SOA
27.EJB3
28.Spring
29.PDF
30.Email
31.J2ME
32.J2EE Application
33.XML
34.Design Pattern
35.Log
36.Security
37.Apache Common
38.Ant
39.JUnit
Java Tutorial » Network » Socket 




  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((chari);
          }
          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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.