java.net Package

Networking classes for TCP sockets and URL handling.

Socket

TCP client socket for connecting to servers.

Constructor

Socket(String host, int port)

Creates a socket and connects to the specified host and port.

Methods

InputStream getInputStream()

Returns an input stream for reading from the socket.

OutputStream getOutputStream()

Returns an output stream for writing to the socket.

InetAddress getInetAddress()

Returns the address to which the socket is connected.

int getPort()

Returns the remote port number.

int getLocalPort()

Returns the local port number.

void close()

Closes the socket.

boolean isClosed()

Returns true if the socket is closed.

boolean isConnected()

Returns true if the socket is connected.

Socket socket = new Socket("example.com", 80);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();

// Send HTTP request
String request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
out.write(request.getBytes());

// Read response
BufferedReader reader = new BufferedReader(
    new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}
socket.close();

ServerSocket

TCP server socket that listens for incoming connections.

Constructor

ServerSocket(int port)

Creates a server socket bound to the specified port.

Methods

Socket accept()

Listens for a connection and accepts it. Blocks until a client connects.

int getLocalPort()

Returns the port on which this socket is listening.

void close()

Closes the server socket.

boolean isClosed()

Returns true if the socket is closed.

ServerSocket server = new ServerSocket(8080);
System.out.println("Server listening on port 8080");

while (true) {
    Socket client = server.accept();
    System.out.println("Client connected: " + client.getInetAddress());

    // Handle client in a new thread
    Thread handler = new Thread(() -> {
        handleClient(client);
    });
    handler.start();
}

InetAddress

Represents an IP address.

Static Methods

static InetAddress getByName(String host)

Determines the IP address of a host by name or IP string.

static InetAddress getLocalHost()

Returns the address of the local host.

static InetAddress getLoopbackAddress()

Returns the loopback address (127.0.0.1).

Instance Methods

String getHostAddress()

Returns the IP address string.

String getHostName()

Returns the host name.

InetAddress addr = InetAddress.getByName("example.com");
System.out.println("IP: " + addr.getHostAddress());
System.out.println("Host: " + addr.getHostName());

InetAddress local = InetAddress.getLocalHost();
System.out.println("Local: " + local.getHostAddress());

URL

Represents a Uniform Resource Locator.

Constructor

URL(String spec)

Creates a URL from the specified string.

Methods

String getProtocol()

Returns the protocol name (e.g., "http", "https").

String getHost()

Returns the host name.

int getPort()

Returns the port number, or -1 if not specified.

String getPath()

Returns the path part of the URL.

String getQuery()

Returns the query string.

String getFile()

Returns the file name (path + query).

InputStream openStream()

Opens a connection and returns an input stream for reading.

String toString()

Returns the string form of the URL.

URL url = new URL("https://example.com:8080/path?query=value");
System.out.println("Protocol: " + url.getProtocol()); // https
System.out.println("Host: " + url.getHost());         // example.com
System.out.println("Port: " + url.getPort());         // 8080
System.out.println("Path: " + url.getPath());         // /path
System.out.println("Query: " + url.getQuery());       // query=value

Simple HTTP Client Example

public class HttpClient {
    public static void main(String[] args) {
        Socket socket = new Socket("example.com", 80);

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));

        // Send request
        out.println("GET / HTTP/1.1");
        out.println("Host: example.com");
        out.println("Connection: close");
        out.println();

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

        socket.close();
    }
}

Simple TCP Server Example

public class EchoServer {
    public static void main(String[] args) {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("Echo server started on port 9999");

        while (true) {
            Socket client = server.accept();

            BufferedReader in = new BufferedReader(
                new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(
                client.getOutputStream(), true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println("Echo: " + line);
            }

            client.close();
        }
    }
}

Threaded Web Server Example

public class WebServer {
    public static void main(String[] args) {
        ServerSocket server = new ServerSocket(8080);

        while (true) {
            Socket client = server.accept();

            Thread handler = new Thread(() -> {
                handleRequest(client);
            });
            handler.start();
        }
    }

    static void handleRequest(Socket client) {
        BufferedReader in = new BufferedReader(
            new InputStreamReader(client.getInputStream()));
        PrintWriter out = new PrintWriter(
            client.getOutputStream(), true);

        // Read request
        String requestLine = in.readLine();

        // Send response
        String html = "<html><body><h1>Hello!</h1></body></html>";
        out.println("HTTP/1.1 200 OK");
        out.println("Content-Type: text/html");
        out.println("Content-Length: " + html.length());
        out.println();
        out.println(html);

        client.close();
    }
}