T E C h O C E A N H U B

Socket programming

Socket programming in Java allows you to establish network communication between two computers over the Internet or a local network. It enables applications to send and receive data through network sockets, which are endpoints for communication.

Here’s a basic example of socket programming in Java:

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

public class Server {
    public static void main(String[] args) {
        try {
            // Create a server socket and bind it to a specific port
            ServerSocket serverSocket = new ServerSocket(1234);
            
            // Wait for client connection
            System.out.println("Waiting for client connection...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected.");
            
            // Create input and output streams for the socket
            InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream();
            
            // Read data from the client
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String clientData = reader.readLine();
            System.out.println("Client sent: " + clientData);
            
            // Send a response back to the client
            PrintWriter writer = new PrintWriter(outputStream, true);
            writer.println("Hello, client!");
            
            // Close the connections
            writer.close();
            reader.close();
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The above code demonstrates a simple server that listens on port 1234 for incoming client connections. When a client connects, it reads data from the client, prints it to the console, and sends a response back to the client.

To connect to the server, you can use the following client code:

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

public class Client {
    public static void main(String[] args) {
        try {
            // Create a client socket and connect to the server
            Socket socket = new Socket("localhost", 1234);
            
            // Create input and output streams for the socket
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            
            // Send data to the server
            PrintWriter writer = new PrintWriter(outputStream, true);
            writer.println("Hello, server!");
            
            // Read the server's response
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String serverResponse = reader.readLine();
            System.out.println("Server response: " + serverResponse);
            
            // Close the connections
            writer.close();
            reader.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the client code, you create a socket and connect to the server running on “localhost” (your own machine) at port 1234. You can modify the host and port values to connect to a server on a different machine.

The client sends a message to the server, reads the server’s response, and prints it to the console.

Note: Socket programming involves handling exceptions and ensuring proper resource cleanup. The code snippets provided demonstrate the basic structure and flow but omit some error handling and exception management for brevity. In a real-world scenario, you should handle exceptions and close resources properly to ensure the reliability and stability of your network applications.

Copyright ©TechOceanhub All Rights Reserved.