I'm working on a Java application that involves socket communication, and I'm trying to create a Thread subclass,calling it CommandThread, which reads commands from a Socket. The valid commands include "DELAY n" and "QUIT."
I have a few questions and concerns:
How can I improve the error handling in the processCommand method? Is there a better way to structure the code for reading and processing commands from the socket? Any general advice on best practices for handling sockets in a multi-threaded environment? I appreciate any insights, suggestions, or corrections you can provide! Thank you.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class CommandThread extends Thread {
private final Socket clientSocket;
private boolean isRunning;
public CommandThread(Socket clientSocket) {
this.clientSocket = clientSocket;
this.isRunning = true;
}
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
while (isRunning) {
String command = reader.readLine();
if (command != null) {
processCommand(command, writer);
}
}
// Clean up resources
reader.close();
writer.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processCommand(String command, PrintWriter writer) {
if (command.startsWith("DELAY ")) {
try {
int delayTime = Integer.parseInt(command.substring(6));
Thread.sleep(delayTime);
writer.println("OK");
} catch (InterruptedException | NumberFormatException e) {
writer.println("ERROR");
}
} else if (command.equals("QUIT")) {
writer.println("BYE");
isRunning = false;
} else {
writer.println("INVALID COMMAND");
}
}
public static void main(String[] args) {
// Usage example:
// In your server code, when a new client connects, create a CommandThread for that client.
// CommandThread commandThread = new CommandThread(clientSocket);
// commandThread.start();
}
}
How can I improve the error handling?
use
try-with-resourcesin your run method please.Is there a better way to structure the code for reading and processing commands from the socket? Any general advice on best practices for handling sockets in a multi-threaded environment?
Use thread pool instead of new thread, this allows for better reuse of server resources
Your code is written in BIO mode, use NIO or AIO for better performance.
Use Reactor pattern to write your code, you can learn more from Netty[https://netty.io/index.html].
Here is an simple example written in Java nio, and you can do better if you use Netty.