基于多线程的Java Socket编程:实现最多5客户端的字符串转大写服务
Solution: Chat App with Uppercase Conversion, Client Limits, and Message Caps
Got it, let's tweak your existing chat application to hit all your requirements: server converts messages to uppercase, max 5 concurrent clients, and each client can send at most 2 messages. Below are the modified client and server codes, plus breakdowns of the key changes.
Modified Client Code
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) throws IOException { System.out.println("Client started.."); Socket socket = new Socket("127.0.0.1", 22222); System.out.println("Client Connected.."); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Scanner sc = new Scanner(System.in); int messageCount = 0; // Restrict to 2 messages per client while (messageCount < 2) { System.out.print("Enter message (" + (2 - messageCount) + " left): "); String message = sc.nextLine(); // Keep exit option for early termination if(message.equals("exit")){ break; } oos.writeObject(message); messageCount++; try { Object fromServer = ois.readObject(); System.out.println("From Server: " + (String) fromServer); } catch (ClassNotFoundException e) { e.printStackTrace(); } } // Send null to signal server we're done oos.writeObject(null); System.out.println("Client closing connection.."); socket.close(); sc.close(); } }
Modified Server Code
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { // Max concurrent clients allowed private static final int MAX_CLIENTS = 5; private static int activeClients = 0; public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(22222); System.out.println("Server Started.."); while (true) { Socket socket = serverSocket.accept(); // Thread-safe check for client limit synchronized (Server.class) { if (activeClients >= MAX_CLIENTS) { System.out.println("Max clients reached, rejecting new connection.."); socket.close(); continue; } activeClients++; } System.out.println("Client connected.. Active clients: " + activeClients); new ServerThread(socket); } } // Update active count when a client disconnects public static void decrementActiveClients() { synchronized (Server.class) { activeClients--; } System.out.println("Client disconnected.. Active clients: " + activeClients); } } class ServerThread implements Runnable { Socket clientSocket; Thread t; ServerThread(Socket clientSocket) { this.clientSocket = clientSocket; t = new Thread(this); t.start(); } @Override public void run() { try { ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); int receivedMessageCount = 0; // Handle up to 2 messages per client while (receivedMessageCount < 2) { Object cMsg = ois.readObject(); // Null means client wants to end the connection if (cMsg == null) { break; } String clientMessage = (String) cMsg; System.out.println("From Client: " + clientMessage); // Convert to uppercase and send back String serverMsg = clientMessage.toUpperCase(); oos.writeObject(serverMsg); receivedMessageCount++; } } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } finally { try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } // Notify server to reduce active client count Server.decrementActiveClients(); } } }
Key Changes Explained
Client Side
- Added a
messageCountcounter to enforce the 2-message limit, updating the loop condition to stop after 2 messages - Added a user-friendly prompt showing how many messages are left to send
- Sends a
nullobject to the server when done, giving a clear signal to close the connection - Properly closes the
Scannerresource to avoid memory leaks
Server Side
- Added
MAX_CLIENTSconstant andactiveClientscounter with synchronized blocks to ensure thread-safe tracking of concurrent connections - Rejects new clients when the active count hits 5, immediately closing their socket
- Each client thread uses
receivedMessageCountto stop processing after 2 messages - Listens for the
nulltermination signal from clients to clean up connections gracefully - Uses a
finallyblock to guarantee the active client count is decremented when a client disconnects, even if an error occurs
内容的提问来源于stack exchange,提问作者Fozle Rabbi
相关产品推荐
相关产品推荐

