我做了我的客户端-服务器应用程序,但目前只有一个用户可以使用它。你能帮我如何让它为多个用户工作。我有以下功能: 每两分钟计数器开始减少。每个用户有 30 秒的时间连接到应用程序。每个连接的用户都应该看到相同的结果,他应该使用这些结果进行一些其他操作。我现在是通过这种方式做到的。不同情况下的代码并不那么重要。我需要一个建议如何使它作为代码的结构工作。提前致谢!
import java.net.*;
import java.io.*;
public class MultiServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening)
new MultiServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
import java.net.*;
import java.io.*;
import java.util.HashMap;
public class MultiServerThread extends Thread {
private Socket socket = null;
public MultiServerThread(Socket socket) {
super("MultiServerThread");
this.socket = socket;
}
public void run() {
try {
ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream fromServer = new ObjectInputStream(socket.getInputStream());
int userProcess = 0;
Object data = 11111;
boolean listening = true;
CountDown c = new CountDown();
int timeRemaining = 900;
while (listening) {
boolean send = true;
Object ob;
try {
ob = fromServer.readObject();
userProcess = Integer.parseInt(ob.toString());
HashMap<String,Integer> finalScores = new HashMap<String,Integer>();
if(userProcess == 0) {
timeRemaining = c.getRemainingTime();
int temp = 999;
while(timeRemaining-110>0) {
timeRemaining = c.getRemainingTime();
if(temp != timeRemaining) {
toServer.writeObject(timeRemaining-110);
toServer.flush();
temp = timeRemaining;
}
}
}
if(userProcess == 0 && timeRemaining-110 < 0) {
c = new CountDown();
send = false;
}
if(userProcess == 1) {
BoardGeneraor board = new BoardGeneraor();
data = board.getBoard();
}
if(userProcess == 2) {
int score = (Integer)fromServer.readObject();
String username = (String)fromServer.readObject();
finalScores.put(username, score);
data = finalScores;
c = new CountDown();
}
if(send) {
toServer.writeObject(data);
toServer.flush();
} else {
toServer.writeObject("quit");
toServer.flush();
}
} catch (ClassNotFoundException e) {
System.out.println(e);
}
}
fromServer.close();
toServer.close();
socket.close();
} catch(IOException e) {
System.out.println(e);
}
}
}