Dis Practical-6

import java.io.*;
import java.net.*;
public class EchoServer {
    public static void main(String[] args) {
        int port = 12345; // Port number for the server
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Echo Server is running on port " + port);
             while (true) {
                try (Socket clientSocket = serverSocket.accept()) {
                    System.out.println("Client connected: " + clientSocket.getInetAddress());
                    handleClient(clientSocket);
                } catch (IOException e) {
                    System.out.println("Error handling client: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.out.println("Error starting server: " + e.getMessage());
        }
    }
 private static void handleClient(Socket clientSocket) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
              String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("Received: " + inputLine);
                out.println(inputLine); // Echo back the received message
            }
        } catch (IOException e) {
            System.out.println("Error in client communication: " + e.getMessage());
        }
    }
}

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

public class EchoClient {
    public static void main(String[] args) {
        String hostname = "localhost"; // Server hostname
        int port = 12345; // Server port number
        try (Socket socket = new Socket(hostname, port);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
             System.out.println("Connected to the Echo Server. Type messages to send:");
 String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput); // Send user input to the server
                String response = in.readLine(); // Read the echoed response from the server
                System.out.println("Echo from server: " + response);
            }
        } catch (IOException e) {
            System.out.println("Error in client: " + e.getMessage());
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top