我正在实现一个多线程 UDP 客户端-服务器字典。我想我已经正确实现了它,但我不知道如何正确测试它。如果有人有时间,您能快速看一下我的代码吗?
这就是我通常运行程序的方式:
java DictServer <port> <dictionary file name>
java DictClient localhost <port> <word to search>
这是服务器的输出(客户端在这里运行了 3 次):
Server Started
Number of threads active: 1
Number of threads active: 2
Number of threads active: 3
Number of threads active: 4
Number of threads active: 5
Thread-0 just run.
Number of threads active: 5
Thread-1 just run.
Number of threads active: 5
Thread-3 just run.
Number of threads active: 5
如您所见,输出看起来不错。我将线程数保持在最大值 (5),因为它是一个“工作池模型”。然而,在 UDP 中,没有“活动连接”,只有发送和接收的数据包。一旦客户端得到它的数据包,线程就关闭了。这发生得非常快,所以我实际上无法同时测试多个客户端连接。有什么建议么?
我还使用 setter 来更新线程数。但是我使用
“DictServer.decNumThreads()”调用它,这很糟糕吗?
我的代码:
服务器类:
public class DictServer {
private static int threads = 0;
public static void main(String args[]) throws IOException {
// Connection Parameters
DatagramSocket socket = null;
int maxThreads = 5; // Max threads at any time
// Retrieve user input
int serverPort = Integer.parseInt(args[0]); // Convert string to int
String dictionaryFile = args[1];
try {
// Setup socket
socket = new DatagramSocket(serverPort);
System.out.println("Server Started");
while(true) {
if(threads < maxThreads) {
ServerThread server = new ServerThread(socket, dictionaryFile);
new Thread(server).start();
threads++;
System.out.println("Number of threads active: " + threads);
}
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
if(socket != null)
socket.close();
}
}
// Setter for number of active threads
public static void decNumThreads() {
threads--;
}
}
线程类:
public class ServerThread implements Runnable {
private DatagramSocket socket = null;
private String dictionaryFile;
// Constructor
public ServerThread(DatagramSocket socket, String dictionaryFile) {
this.socket = socket;
this.dictionaryFile = dictionaryFile;
}
@Override
public void run() {
byte[] word = new byte[1000];
byte[] definition = new byte[1000];
try {
// Get client request
DatagramPacket request = new DatagramPacket(word, word.length);
socket.receive(request);
// Retrieve definition from dictionary file
if(word != null)
definition = getDefinition(new String(word), dictionaryFile);
// Put reply into packet, send packet to client
DatagramPacket reply = new DatagramPacket(definition, definition.length, request.getAddress(), request.getPort());
socket.send(reply);
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println(Thread.currentThread().getName() + " just run.");
DictServer.decNumThreads();
}