Java · Java Intermediate

Java Networking: Sockets, TCP/IP, and UDP

Run this in the Online Java compiler

Hello, Java network programmers!

Today's topic is Java Networking, focusing on Sockets, TCP/IP, and UDP. Networking in Java allows you to manage multiple activities over a network like reading and writing from and to a server through sockets.

1. Sockets

A socket is an endpoint for communication between two machines. Java provides two types of socket classes: Socket (for client-side) and ServerSocket (for server-side).

2. TCP/IP

TCP/IP (Transmission Control Protocol/Internet Protocol) is a suite of communication protocols used to interconnect network devices on the internet. TCP is a connection-oriented protocol, whereas UDP (User Datagram Protocol) is a simpler, connectionless internet protocol.

Example of a TCP Server and Client in Java:

TCP Server:

java
Copy code
import java.io.*;
import java.net.*;
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("Server started");
        Socket socket = serverSocket.accept(); // Establishes connection
        System.out.println("Client connected");
        // Receiving data from client
        DataInputStream in = new DataInputStream(socket.getInputStream());
        System.out.println("Client says: " + in.readUTF());
        serverSocket.close();
    }
}

TCP Client:

java
Copy code
import java.io.*;
import java.net.*;
public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 6666);
        System.out.println("Connected to server");
        // Sending data to server
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        out.writeUTF("Hello Server");
        socket.close();
    }
}

In this example, the server listens on port 6666. When the client connects to this server, the server accepts the connection, and the client sends a message.

Exercise: Create a Simple Client-Server Application

Your task is to create a simple client-server application using Java Sockets:

The server should listen on a specific port and be able to handle multiple client requests.The client should connect to the server, send a message (like "Hello, Server!"), and then close the connection.The server, upon receiving a message, should print it out and then wait for the next connection.Conclusion

Great job! You've just learned the basics of Java networking with TCP/IP sockets. Networking is a fundamental concept in Java for building distributed applications and services.

Experiment with this client-server model, perhaps by expanding the functionality to include more complex interactions or handling multiple clients concurrently.

Enjoy coding and exploring the vast world of Java networking!

This website uses cookies to ensure you get the best experience on our website.