Java Networking


Java Networking allows Java applications to exchange data between different devices via TCP/IP network connections.

 

The Java socket programming framework enables data transmission between multiple computing devices.

java-networking

notepad

The java.net package provides Java with straightforward capabilities to manage networking tasks.


Types of Communication

TCP (Transmission Control Protocol)

  • Reliable and connection-oriented
  • Classes: Socket, ServerSocket

UDP (User Datagram Protocol)

  • Fast, but connectionless and unreliable
  • Classes: DatagramSocket, DatagramPacket

Example

Server Code

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

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5000);
        System.out.println("Server is waiting...");

        Socket socket = serverSocket.accept();  // Accept client
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        String message = dis.readUTF();

        System.out.println("Client says: " + message);

        dis.close();
        socket.close();
        serverSocket.close();
    }
} 

Client Code

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

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 5000);
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

        dos.writeUTF("Hello, Server!");
        dos.close();
        socket.close();
    }
} 

Output

Server is waiting...
Client says: Hello, Server!



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.