This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 8, 2023

How socket class can be used in socket program? Write client-server chat programs in java.

 In Java, the Socket class can be used to create a socket and communicate with a remote server or client over a network. The ServerSocket class can be used to create a server socket that listens for incoming connections from clients.

Here are the basic steps to create a client-server chat program using sockets in Java:

Create a server program:

The server program creates a ServerSocket object and listens for incoming connections from clients. When a client connects, the server accepts the connection and creates a new thread to handle communication with the client.

For example:

import java.net.*;
import java.io.*;
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5000);
        System.out.println("Server started on port 5000");
        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("New client connected");
            ClientHandler clientHandler = new ClientHandler(clientSocket);
            clientHandler.start();
        }
    }
}
class ClientHandler extends Thread {
    private Socket clientSocket;
    private BufferedReader in;
    private PrintWriter out;
    public ClientHandler(Socket socket) throws IOException {
        clientSocket = socket;
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new PrintWriter(clientSocket.getOutputStream(), true);
    }
    public void run() {
        try {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("Received message from client: " + inputLine);
                out.println("Server received message: " + inputLine);
            }
        } catch (IOException e) {
            System.err.println("Error handling client: " + e);
        } finally {
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("Error closing client socket: " + e);
            }
        }
    }
}

Create a client program:

The client program creates a Socket object and connects to the server. The client can send messages to the server and receive messages from the server.

For example:

import java.net.*;
import java.io.*;
public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 5000);
        System.out.println("Connected to server");
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        String userInput;
        while ((userInput = console.readLine()) != null) {
            out.println(userInput);
            System.out.println("Server response: " + in.readLine());
        }
        in.close();
        out.close();
        socket.close();
    }
}

In this example, the client sends a message to the server by typing it into the console and hitting enter. The server receives the message, prints it to the console, and sends a response back to the client. The client receives the response and prints it to the console. The client can continue sending messages to the server until it terminates the connection.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget