正如标题所示,我正在实现一个小项目,它允许客户端使用多线程连接到服务器来管理连接。我想限制连接,当服务器充满请求时,其他客户端应该放在一个队列中,例如:服务器只允许 2 个客户端同时连接服务器,其他客户端直到轮到他们。
这是我的服务器类
public class Server {
static BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
//Declare an instance of CommandParameter class
static CommandParameter par;
//Initialize a BufferedReader and BufferedWriter
static BufferedReader bufferedReader;
static BufferedWriter bufferWriter;
//
static int port;
static String serverData;
static int proc_count;
private static String command;
public static void main(String[] args) throws Exception {
command = userInput.readLine();
System.out.println("Server is available");
//Thread.sleep(2000);
processCommand(command);
startServer(port);
}
public static void startServer(int port) {
ServerSocket serverSocket = null;
try {
//create a port for server in order to listen incoming connections
serverSocket = new ServerSocket(port);
//allow client connect to server
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
new ThreadSocket(serverSocket.accept(),serverData).start();
} catch (IOException ex) {
System.out.println("Server starts fail");
}
}
}
public static void processCommand(String input) {
//assign the user input to an String array
String inputLine = input;
int commandCount = checkCommand(inputLine);
if(commandCount>3 || commandCount ==-1){
System.out.println("Invalid command");
System.exit(1);
}
//assign the user input to an String array
String[] command = inputLine.split(" ");
par = new CommandParameter();
//JCommander parses the command to get the pairs parameter name and value
JCommander jc = new JCommander(par, command);
port = par.getPort();
serverData = par.getServerdata();
proc_count = par.getProc_count();
}
public static int checkCommand(String inputLine) {
int count = 0;
if (inputLine.contains("-port")) {
count++;
}else if (inputLine.contains("-data")) {
count++;
} else if (inputLine.contains("-proc_count")) {
count++;
} else{
return -1;
}
return count;
}
}
有任何想法吗?