我想用線程建立一個多端口服務器。我也有一個ClientManager類和一個客戶端類。需要發生的事情是用戶輸入一系列端口......比如端口8000-8010。服務器需要監聽所有這些端口的連接。 ClientManager然後獲取端口範圍併爲每個端口創建一個Client實例。然後客戶端以0-1秒的間隔隨機發送消息到服務器。客戶端發送100條消息後,應斷開連接。服務器需要每5秒打印一次收到的消息數量。建立一個多端口服務器:Java
到目前爲止,我已經設法獲取端口範圍的用戶輸入,然後通過Runtime.exec()參數將它們發送到ClientManager。這裏是我當前的代碼爲服務器和ClientManager:
import java.io.*;
public class Server{
public static void main(String[] args){
try{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader userInputReader = new BufferedReader(isr);
String lowPortRange = null;
String highPortRange = null;
System.out.println("Enter low end of port range:");
if((lowPortRange = userInputReader.readLine())!=null){
System.out.println("Low Range: " + lowPortRange);
}
System.out.println("Enter high end of port range:");
if((highPortRange = userInputReader.readLine()) != null){
System.out.println("High Range: " + highPortRange);
}
int lowPort = Integer.parseInt(lowPortRange);
int highPort = Integer.parseInt(highPortRange);
int totalPorts = highPort - lowPort+1;
System.out.println("Total ports: " + totalPorts);
System.out.println("...Port numbers...");
for(int port = lowPort; port<=highPort; port++){
System.out.println(port);
}
System.out.println("Done!");
System.out.println();
Process p = Runtime.getRuntime().exec("java ClientManager " + lowPort + " " + highPort);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}catch(IOException e){
System.out.println("IOException!");
e.printStackTrace();
}
}
}
import java.io.*;
public class ClientManager{
private int lowPort;
private int numPorts;
public static void main(String[] args){
System.out.println("ClientManager Started.");
int firstPort = Integer.parseInt(args[0]);
int lastPort = Integer.parseInt(args[1]);
System.out.println("First Port: " + firstPort);
System.out.println("Last Port: " + lastPort);
}
}
我的問題基本上是這樣的:可能有人解釋,從理論上講,我應該何去何從?
服務器關閉確實需要優雅地完成。 –
然後,您還必須確保所有線程都有某種關閉條件,而不是永遠循環 - 當沒有更多服務器套接字線程存在時的主線程,服務器線程完成處理客戶端連接時的線程。 – millimoose