所以我试图创建一个多人战舰游戏。目前我为每个客户提供了一个帖子,但我想知道,一旦我将两个客户端配对,我会将它们放入游戏的新线程中吗?如果是这样,我会将客户端线程存储在游戏线程中还是仅存储在套接字中。 ObjectInput和Output流位于clientThreads内部,一旦gameThread启动,我无法从中读取它们。
服务器:
public static void startGame(String player1, String player2) {
matchCount++;
ClientThread c1 = connectedClients.get(player1);
ClientThread c2 = connectedClients.get(player2);
try {
c1.serverOut.writeObject(protocol.createMessage("send-invite", "true", "Match Started."));
c1.serverOut.flush();
c2.serverOut.writeObject(protocol.createMessage("send-invite", "true", "Match Started."));
c2.serverOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
lobbyList.remove(c1.player.getUserName());
connectedClients.remove(c1.player.getUserName());
c1.signedIn = false;
c1.inGame = true;
lobbyList.remove(c2.player.getUserName());
connectedClients.remove(c2.player.getUserName());
c2.signedIn = false;
c2.inGame = true;
sendUpdatedList();
GameThread game = new GameThread(c1, c2);
gameList.put(matchCount, game);
gamePool.execute(game);
}
ClientThread:
public class ClientThread implements Runnable {
boolean signedIn = false;
boolean inGame = false;
private Object received;
ObjectInputStream serverIn;
ObjectOutputStream serverOut;
Player player;
Socket clientSocket;
private SimpleProtocol protocol;
private Database user;
/**
* @param socket
*/
ClientThread(Socket socket) {
clientSocket = socket;
this.protocol = new SimpleProtocol();
try {
this.serverIn = new ObjectInputStream(new BufferedInputStream(clientSocket.getInputStream()));
this.serverOut = new ObjectOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
serverOut.writeObject(protocol.createMessage("send-message", "Welcome to the Server."));
serverOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
...
GameThread:
public class GameThread implements Runnable {
private ArrayList<String> inGameMessages = new ArrayList<>();
private ClientThread client1;
private ClientThread client2;
private Player player1 = null;
private Player player2 = null;
private SimpleProtocol protocol = new SimpleProtocol();
/**
* @param client1
* @param client2
*/
public GameThread(ClientThread client1, ClientThread client2) {
this.client1 = client1;
this.client2 = client2;
}
@Override
public void run() {
try {
Object received1 = client1.serverIn.readObject(); //This never seems to run
Object received2 = client2.serverIn.readObject();
....