【发布时间】:2019-05-27 08:42:47
【问题描述】:
我正在编写简单的 Java 服务器,它只连接 5 个用户并运行简单的游戏。 我的问题是与客户端通信,因为 Game 对象位于主线程中,并且每个子线程都获取有关特定玩家移动(1-5 id)的信息。我不知道如何将此信息发送到主线程并更新游戏状态。
我的代码是否正确,不存在任何大错误(这是我的第一个多任务项目),以及我应该如何与主线程通信
Player.java
package Model;
import java.io.*;
import java.net.Socket;
public class Player extends Thread{
private long id;
private Socket clientSocket;
private InputStream clientInput;
private BufferedReader clientIn;
private DataOutputStream clientOut;
private String nickname;
private boolean isReady;
public Player(long id, Socket clientSocket) throws IOException {
this.id = id;
this.clientSocket = clientSocket;
this.clientInput = this.clientSocket.getInputStream();
this.clientIn = new BufferedReader(new InputStreamReader(this.clientInput));
this.clientOut = new DataOutputStream(this.clientSocket.getOutputStream());
this.isReady = false;
clientOut.writeBytes("POLACZONO\n");
clientOut.flush();
}
public void run() {
boolean isCorrect = false;
try {
while(!isCorrect) {
String login = this.clientIn.readLine();
if (!login.equals("") && login.startsWith("LOGIN") && login.length() > 6) {
this.clientOut.writeBytes("OK\n");
this.clientOut.flush();
setNickname(login.substring(login.indexOf(" ") + 1));
isCorrect = true;
this.isReady = true;
} else if (!login.equals("") && (!login.startsWith("LOGIN") || login.length() <= 6)) {
this.clientOut.writeBytes("ERROR\n");
this.clientOut.flush();
}
}
while (true) {
//DATA FROM CLIENT
}
//this.clientOut.writeBytes("START " + this.id + " " + startPlayer + "\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
this.clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
主线程
public void startServer(ServerSocket serverSocket) throws IOException {
playerList = Collections.synchronizedList(new ArrayList<Player>());
int remaining = 1;
while (true) {
if(playerList.size() < 5) {
while (playerList.size() < 5) {
Socket connectionSocket = serverSocket.accept();
playerList.add(new Player(remaining, connectionSocket));
playerList.get(playerList.size() - 1).start();
remaining++;
}
}
final int startPlayer;
if(!playerList.stream().noneMatch(x -> x.isReady())) {
startPlayer = new Random().nextInt((5 - 1) + 1) + 1;
for (Player player : playerList) {
player.getClientOut().writeBytes("START " + player.getId() + " " + startPlayer + "\n");
}
//GAME START
}
}
}
【问题讨论】:
标签: java multithreading sockets server communication