WikiGalaxy

Personalize

Java Networking Components

Socket Programming

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.


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

public class Client {
  public static void main(String[] args) {
    try {
      Socket clientSocket = new Socket("localhost", 6789);
      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      
      outToServer.writeBytes("Hello from Client\n");
      String response = inFromServer.readLine();
      System.out.println("FROM SERVER: " + response);
      
      clientSocket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

FROM SERVER: Welcome to the Server

DatagramSocket and DatagramPacket

UDP Communication

Java provides the DatagramSocket class for UDP communication. Unlike TCP, UDP is connectionless and does not guarantee delivery, order, or error checking.


import java.net.*;

public class UDPSender {
  public static void main(String[] args) {
    try {
      DatagramSocket socket = new DatagramSocket();
      String message = "Hello UDP";
      byte[] buffer = message.getBytes();
      
      InetAddress receiverAddress = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length, receiverAddress, 9876);
      
      socket.send(packet);
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

Message sent via UDP

URL and URLConnection

Accessing Web Resources

The URL class represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. You can read directly from a URL using URLConnection.


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

public class URLExample {
  public static void main(String[] args) {
    try {
      URL url = new URL("https://www.example.com");
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      
      String inputLine;
      while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
      }
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

HTML content from the URL

Multithreaded Server

Handling Multiple Clients

A multithreaded server can handle multiple clients simultaneously by spawning a new thread for each connection request.


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

public class MultiThreadedServer {
  public static void main(String[] args) {
    try {
      ServerSocket serverSocket = new ServerSocket(6789);
      while (true) {
        Socket connectionSocket = serverSocket.accept();
        new Thread(new ClientHandler(connectionSocket)).start();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

class ClientHandler implements Runnable {
  private Socket connectionSocket;

  public ClientHandler(Socket socket) {
    this.connectionSocket = socket;
  }

  public void run() {
    try {
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
      
      String clientMessage = inFromClient.readLine();
      System.out.println("Received: " + clientMessage);
      outToClient.writeBytes("Hello Client\n");
      
      connectionSocket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

Received: Hello from Client

HTTP Client

Sending HTTP Requests

Java's HttpURLConnection allows the sending of HTTP requests and receiving of HTTP responses from a resource identified by a URL.


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

public class HTTPClientExample {
  public static void main(String[] args) {
    try {
      URL url = new URL("https://jsonplaceholder.typicode.com/posts");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("GET");
      
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String inputLine;
      StringBuffer content = new StringBuffer();
      while ((inputLine = in.readLine()) != null) {
        content.append(inputLine);
      }
      in.close();
      System.out.println(content.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

JSON data from the URL

Secure Communication with SSL

Using SSLSocket

SSLSocket provides a secure communication channel between the client and server by utilizing the Secure Sockets Layer (SSL) protocol.


import javax.net.ssl.*;
import java.io.*;

public class SSLClient {
  public static void main(String[] args) {
    try {
      SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      SSLSocket socket = (SSLSocket) factory.createSocket("localhost", 9999);
      
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      
      out.write("Hello Secure Server\n");
      out.flush();
      System.out.println("Server says: " + in.readLine());
      
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

Server says: Welcome to Secure Server

MulticastSocket for Group Communication

Group Communication

MulticastSocket is a subclass of DatagramSocket, used for sending and receiving IP multicast packets. It is useful for group communication.


import java.net.*;

public class MulticastSender {
  public static void main(String[] args) {
    try {
      MulticastSocket socket = new MulticastSocket();
      InetAddress group = InetAddress.getByName("230.0.0.0");
      String message = "Hello Multicast";
      DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), group, 4446);
      
      socket.send(packet);
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

Multicast message sent

NetworkInterface for Network Interfaces

Inspecting Network Interfaces

The NetworkInterface class represents a network interface made up of a name and a list of IP addresses assigned to this interface.


import java.net.*;
import java.util.*;

public class NetworkInterfaces {
  public static void main(String[] args) {
    try {
      Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
      while (interfaces.hasMoreElements()) {
        NetworkInterface ni = interfaces.nextElement();
        System.out.println("Interface: " + ni.getName());
        
        Enumeration addresses = ni.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress address = addresses.nextElement();
          System.out.println("Address: " + address.getHostAddress());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

Interface: eth0 Address: 192.168.1.1

Proxy Settings in Java

Configuring Proxy for HTTP

Java provides the ability to set proxy settings for HTTP connections, allowing the application to route requests through a proxy server.


import java.net.*;

public class ProxyExample {
  public static void main(String[] args) {
    try {
      Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
      URL url = new URL("http://www.example.com");
      HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
      
      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
      }
      in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

HTML content via proxy

Java NIO for Networking

Non-blocking I/O

Java NIO offers features like non-blocking I/O operations, which allow you to build scalable network applications.


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
  public static void main(String[] args) {
    try {
      InetSocketAddress hostAddress = new InetSocketAddress("localhost", 5454);
      SocketChannel client = SocketChannel.open(hostAddress);
      
      String message = "Hello NIO Server";
      ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
      client.write(buffer);
      
      buffer.clear();
      client.read(buffer);
      System.out.println("Server response: " + new String(buffer.array()).trim());
      
      client.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
      

Console Output:

Server response: Welcome to NIO

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025