0
我正在實現多線程UDP客戶端 - 服務器字典。我想我已經正確實施了,但我不知道如何正確測試它。如果有人有時間,你能否快速瀏覽一下我的代碼?測試多線程UDP服務器(Java)
這是怎麼了,我通常運行我的程序:
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();
}
你寫了一些代碼,你想我們測試它?自動化您的客戶端並創建您自己的測試系統。當您遇到問題時,請回復代碼,症狀,錯誤消息/異常以及您對該問題進行的調試。 – 2012-08-10 07:52:11
正如我上面提到的,我已經運行了客戶端並收到了正確的輸出。我只是不知道如何測試我的服務器的線程功能,所以我在這裏問了一些見解。我發佈了我的代碼,因爲我認爲這會幫助我得到答案。我會盡力讓我的客戶自動化。 – pakmon 2012-08-10 08:56:14