javanet.Socket, javanet.ServerSocket, and javanetDatagramSocket

In Java, a socket (Socket) is a mechanism for communicating over a network. Java provides several socket classes related to network communication, including java.net.Socket, java.net.ServerSocket and java.net.DatagramSocket . These classes allow Java programs to communicate over networks via TCP and UDP protocols.

  1. java.net.Socket:
    The Socket class represents the communication endpoint between the client and the server. It provides methods for establishing connections, sending and receiving data. Using Socket, the client can connect to the server and send requests, and the server can accept these requests and process them accordingly. Socket is based on the TCP protocol, so it provides reliable, connection-oriented communication.

  2. java.net.ServerSocket:
    The ServerSocket class is a socket class used to monitor and accept client connection requests on the server side. The server usually creates a ServerSocket instance, and calls its accept() method to wait for the client to connect. Once the client connection request arrives, the accept() method will return a new Socket instance, which establishes a communication channel with the client, through which the server can communicate with the client terminal to interact.

  3. java.net.DatagramSocket:
    The DatagramSocket class allows data packet transmission using the UDP protocol. Different from TCP, UDP is a connectionless and unreliable communication protocol, which is suitable for scenarios that require high real-time data transmission but low data reliability requirements. The DatagramSocket class provides methods for sending and receiving data packets.

These socket classes provide a powerful set of tools that enable Java programs to communicate over a network. Clients can use Socket to connect to the server, send requests and receive responses. The server can use ServerSocket to listen to client connection requests, and use Socket to communicate with the client. And DatagramSocket allows the use of UDP protocol for data packet transmission. These classes are very commonly used tools in network programming.

java.net.Socket:

java.net.Socket is a class in Java for client endpoints of TCP (Transmission Control Protocol) based network communications. It allows you to establish a connection to a server (using the server’s IP address and port number), and enables two-way communication between the client and the server. Once the connection is established, you can use Socket’s InputStream and OutputStream to send and receive data.

Example usage:

import java.net.*;

public class ClientExample {<!-- -->
    public static void main(String[] args) {<!-- -->
        try {<!-- -->
            // Create a Socket to connect to the server
            Socket socket = new Socket("localhost", 8080);

            // Get the output stream and send data to the server
            OutputStream outputStream = socket. getOutputStream();
            outputStream.write("Hello, server!".getBytes());

            // Get the input stream and receive data from the server
            InputStream inputStream = socket. getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream. read(buffer);
            String response = new String(buffer, 0, bytesRead);
            System.out.println("Server response: " + response);

            // Close the Socket when done
            socket. close();
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }
}

java.net.ServerSocket:

java.net.ServerSocket is a TCP-based server-side socket in Java. It listens for incoming client connection requests on a specific port and establishes a connection with the client after accepting the connection request. It is used to create server applications capable of accepting incoming client connections using TCP.

Example usage:

import java.net.*;

public class ServerExample {<!-- -->
    public static void main(String[] args) {<!-- -->
        try {<!-- -->
            // Create a ServerSocket to listen for client connections, the port number is 8080
            ServerSocket serverSocket = new ServerSocket(8080);

            System.out.println("Waiting for client connection...");

            // accept client connections
            Socket clientSocket = serverSocket. accept();
            System.out.println("The client is connected: " + clientSocket.getInetAddress());

            // Get the input stream and receive data from the client
            InputStream inputStream = clientSocket. getInputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream. read(buffer);
            String request = new String(buffer, 0, bytesRead);
            System.out.println("Received from client: " + request);

            // Get the output stream and send data to the client
            OutputStream outputStream = clientSocket. getOutputStream();
            outputStream.write("Hello, client!".getBytes());

            // Close the client Socket when done
            clientSocket. close();

            // Close the ServerSocket when done
            serverSocket. close();
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }
}

java.net.DatagramSocket:

java.net.DatagramSocket is a class in Java that allows you to send and receive datagrams (packets of data) over a network using UDP (User Datagram Protocol). Unlike TCP, UDP is a connectionless protocol, where communication is based on sending and receiving individual packets of data (datagrams) without establishing a connection.

Example usage:

import java.net.*;

public class DatagramExample {<!-- -->
    public static void main(String[] args) {<!-- -->
        try {<!-- -->
            // Create a DatagramSocket for sending and receiving datagrams
            DatagramSocket socket = new DatagramSocket();

            // Send data to a specific server and port
            String message = "Hello, server!";
            byte[] sendData = message. getBytes();
            InetAddress serverAddress = InetAddress. getByName("localhost");
            int serverPort = 8080;
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData. length, serverAddress, serverPort);
            socket.send(sendPacket);

            // Receive data from server
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData. length);
            socket.receive(receivePacket);
            String response = new String(receivePacket. getData(), 0, receivePacket. getLength());
            System.out.println("Server response: " + response);

            // Close the Socket when done
            socket. close();
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }
}