Create a multiple client server communication using JAVA
import java.net.*; import java.io.*; class ClientThread extends Thread { private Socket socket; ClientThread(Socket socket) { this.socket = socket; } public void run() { try { DataInputStream data = new DataInputStream(socket.getInputStream()); DataOutputStream output = new DataOutputStream(socket.getOutputStream()); String reply; while (true) { String msg = data.readUTF(); if("exit".equalsIgnoreCase(msg)){ reply = "Good bye..."; output.writeUTF(reply); break; } else { // System.out.println("Message: " + msg); reply = "Your Message: " + msg + "\nMessage Length: " + msg.length(); output.writeUTF(reply); } } socket.close(); } catch (Exception e) { e.printStackTrace(); } } } public class Server { public static void main(String[] args) { try (ServerSocket server = new ServerSocket(5000)) { while (true) { Socket socket = server.accept(); new ClientThread(socket).start(); } } catch (Exception e) { e.printStackTrace(); } } }
The provided Java code represents a simple server program that listens for incoming socket connections on port 5000. Upon accepting a connection, it creates a new thread (`ClientThread`) to handle the communication with the connected client.
The `ClientThread` class extends the `Thread` class and is responsible for managing the communication with a specific client. It uses `DataInputStream` to read messages from the client and `DataOutputStream` to send responses back. The communication is done using the UTF-8 encoding.
The main functionality of the server involves continuously accepting client connections in the `Server` class's `main` method. For each accepted connection, a new instance of `ClientThread` is created and started as a separate thread.
The communication protocol between the server and clients involves reading messages from the client, processing them, and sending a response back. If the client sends the message "exit," the server replies with "Good bye..." and closes the connection. Otherwise, it responds with a message containing the original message and its length.
The server is designed to run indefinitely, continuously accepting new client connections and creating threads to handle each connection. In case of any exceptions during execution, the server prints the stack trace to help diagnose and fix issues.
Note: This code lacks proper error handling and may not be suitable for production use. Additionally, consider using `try-with-resources` for resource management.
0 Comments
Do not make spam in comment box.