Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

TCP/IP Client Sockets, URL, and URLConnection

Lesson 36 of 46 in the free Web Technologies notes on Siksha Sarovar, written by Rohit Jangra.

TCP/IP Client Sockets, URL, and URLConnection

TCP/IP Client Sockets

A socket is one endpoint of a two-way network connection. Java's Socket class implements a client socket — it connects to a server listening on a host and port.

import java.io.*;
import java.net.Socket;

public class TCPClient {
    public static void main(String[] args) throws IOException {
        // Connect to server at host:port
        Socket socket = new Socket("localhost", 5000);

        // Output stream: send data to the server
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hello Server!");

        // Input stream: read the server's reply
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        System.out.println("Server says: " + in.readLine());

        socket.close();
    }
}

Key Socket Methods

MethodPurpose
getInputStream()Stream to read data from the peer
getOutputStream()Stream to send data to the peer
getInetAddress()Remote address the socket is connected to
getPort() / getLocalPort()Remote / local port number
close()Releases the connection
setSoTimeout(int ms)Read timeout in milliseconds

The URL Class

A URL (Uniform Resource Locator) identifies a resource on the Internet. Java's URL class parses and lets you fetch the resource it points to.

import java.net.URL;

public class URLDemo {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.example.com:443/path/page.html?id=1");

        System.out.println("Protocol: " + url.getProtocol()); // https
        System.out.println("Host:     " + url.getHost());     // www.example.com
        System.out.println("Port:     " + url.getPort());     // 443
        System.out.println("File:     " + url.getFile());     // /path/page.html?id=1
        System.out.println("Path:     " + url.getPath());     // /path/page.html
        System.out.println("Query:    " + url.getQuery());    // id=1
    }
}

Reading a URL Directly

import java.io.*;
import java.net.URL;

public class URLReader {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.example.com");
        BufferedReader in = new BufferedReader(
            new InputStreamReader(url.openStream()));

        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();
    }
}

The URLConnection Class

URLConnection gives finer control than openStream() — request headers, response headers, and both reading and writing.

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionDemo {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://www.example.com");
        URLConnection conn = url.openConnection();

        conn.setRequestProperty("User-Agent", "JavaClient/1.0");
        conn.setDoOutput(false);
        conn.connect();

        System.out.println("Content-Type:   " + conn.getContentType());
        System.out.println("Content-Length: " + conn.getContentLength());
        System.out.println("Last Modified:  " + conn.getLastModified());

        BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();
    }
}

URL vs URLConnection

FeatureURLURLConnection
SimplicityopenStream() — one line to readMore verbose, more control
HeadersNot accessibleRequest/response headers accessible
Writing dataNot supportedSupported via setDoOutput(true)
Use caseQuick readsPOST requests, custom headers, metadata
Key Takeaway: Socket gives a raw TCP client connection for custom protocols. URL and URLConnection build on sockets to fetch web resources — use URL.openStream() for quick reads and URLConnection when you need headers or to send data.