我正在爲大學項目開發一個簡單的服務器 - 客戶端骰子游戲。遊戲限制是可以有無數玩家。我試圖創建他們的分數列表,但我不知道如何傳遞玩家數量,因爲每次連接下一個玩家時,服務器都會接受新的連接,所以我無法阻止下一個線程的啓動。java中的多線程 - 未知數量玩家的得分列表
我在想的東西,如「PLAY」按鈕/布爾變量在等待玩家和遊戲開始之後,下一個線程將無法獲得start.However,我不知道如何實現它。有什麼建議麼?另一個想法也將是一個很好的建議:)
下面是從服務器的代碼片段:
public void initializeResultList(int amountOfPlayers){
final ArrayList<Object> resultDescription = new ArrayList();
ArrayList<Object> zeros = new ArrayList();
resultDescription.add("Player");
resultDescription.add("One Pair");
resultDescription.add("Two Pairs");
resultDescription.add("Three of a kind");
resultDescription.add("Full House");
resultDescription.add("Four of a kind");
resultDescription.add("Five of a kind");
for (int j = 0; j < resultDescription.size(); j++){
zeros.add(null);
}
resultList.add(resultDescription);
//fill with nulls, then there will be player Scores
for (int i = 1; i <= amountOfPlayers; i++){
resultList.add(zeros);
}
}
public static void main(String args[]) throws IOException {
int portNumber = 444;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error finding port");
System.exit(1);
}
// program loop
do {
Server server = new Server(serverSocket.accept());
//HERE IS THE PROBLEM!
server.initializeResultList(2); // here should be passed the amount
server.start();
} while (true);
}
@Override
public void run(){
System.out.println("Connection accepted");
System.out.println("Client has successfully connected");
}
下面是從播放器類的代碼(這不是問題的權利,但也許你想知道服務器和播放器如何通信):
public static void main (String args[]) throws IOException {
//Connect to the server
Socket socket = null;
int portNumber = 444;
String str;
BufferedReader br = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = null;
try {
socket = new Socket(InetAddress.getLocalHost(), portNumber);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (UnknownHostException uhe) {
System.out.println("Unknown Host");
System.exit(0);
}
boolean quit = false;
while (!quit) {
str = input.readLine();
out.println(str);
}
}
如果即時讀取您的問題,您可以等待,直到服務器遇到來自客戶端的某種信號以停止處理。即不要只發送原始數據到服務器,而是在服務器上附加一個頭字符串(類似'end-stream:false; data:yourstring'或'end-data:true; data:yourstring')並解析出來。那麼你不需要知道你傳遞的數字,因爲告訴線程何時停止處理是數據本身的一部分。考慮檢查光標模式。 –
嗯,所以你的意思是客戶端做了一些操作,防止服務器連接到更多的線程?我沒有得到這個解決方案與標題字符串:( –
嗯,我認爲你正在試圖處理的根本問題不是與多線程真的做。想想你怎麼可以發送或接收數據集你需要發送一些關於該集合的元數據,這樣你就知道它有多大,或者向服務器發送一個令牌,告訴它該數據集何時結束......實際上,你不需要在你的服務器上使用多線程,實際上,設置這麼多的線程在計算資源方面效率是非常低的 –