我正在尝试使用线程构建多端口服务器。我还有一个 ClientManager 类和一个 Client 类。需要发生的是用户输入了一系列端口……比如说端口 8000-8010。服务器需要在所有这些端口上侦听连接。ClientManager 然后获取端口范围并为每个端口创建一个 Client 实例。然后客户端以 0-1 秒之间的随机间隔向服务器发送消息。客户端发送 100 条消息后,它应该断开连接。服务器需要每 5 秒打印出它收到了多少条消息。
到目前为止,我已经设法获取端口范围的用户输入,然后通过 Runtime.exec() 参数将它们发送到 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);
}
}
我的问题基本上是这样的:有人可以从理论上解释我应该从哪里开始吗?