我正在编写一个多人游戏,并且正在使用套接字在 Java 中为它编写自己的服务器。
我使用 Java 教程和一些谷歌搜索成功地启动并运行了一个服务器,但是当我尝试实现一个多线程服务器来处理多个客户端时,它工作不正常。
第一个连接的客户端仍然可以正常工作,但任何其他连接的客户端在将输入发送到服务器后只会坐在那里,什么也不做。这是我的代码:
//This class handled Server/client communication for one client.
public class GameRoom implements Runnable {
public GameRoom(Socket socket) {
this.socket = socket;
}
public void run() {
logger.info("Game room has been created.");
while(true) {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String clientResponse = in.readLine();
out.println("You wrote " + clientResponse);
out.flush();
} catch (IOException e) {
logger.severe(e.getMessage());
throw new RuntimeException();
}
}
}
//Will eventually change the string to a GSON object and delegate the appropriate actions based on the gson object type.
private String delegateClientInput(String clientInput) {
return "I heard you say: " + clientInput + "\n";
}
private BufferedReader in;
private PrintWriter out;
private Socket socket;
private static final Logger logger = LogUtil.initializeServerLog(GameRoom.class.toString());
}
/*
* This class houses the server socket itself. Handles connecting to multiple clients.
*/
public class ServerClientThreadPool extends Thread {
public static void main(String[] args) {
ServerClientThreadPool serverClientThreadPool = new ServerClientThreadPool();
serverClientThreadPool.startServer();
}
ServerClientThreadPool() {
try {
serverListener = new ServerSocket(GAME_ROOM_PORT);
} catch (IOException e) {
logger.severe(e.getMessage());
throw new RuntimeException();
}
}
public void startServer() {
for(int i = 0; i < MAX_CONNECTIONS; i++) {
try {
GameRoom gameRoom = new GameRoom(serverListener.accept());
gameRoom.run();
} catch (IOException e) {
logger.severe(e.getMessage());
throw new RuntimeException();
}
}
}
private static final int GAME_ROOM_PORT = 18000;
private ServerSocket serverListener;
private static final int MAX_CONNECTIONS = 100;
private static final Logger logger = LogUtil.initializeServerLog(ServerClientThreadPool.class.getName());
}
这是客户端的主要功能,当然位于一个单独的程序中:
ClientSocketWrapper clientSocketWrapper = ClientSocketWrapper.createSocketWrapperAndConnectTo("localhost", 18000);
/** MAIN ENTRY POINT FOR CLIENT */
while(true) {
clientSocketWrapper.updateInputOutputStream();
clientSocketWrapper.writeToOutputStream(executeClientInputProcessing());
updateGameState(clientSocketWrapper.getServerResponse());
}
我意识到您无法真正看到这些方法内部发生了什么,但它基本上只是像 Java 教程那样实现客户端并且它按预期工作。如果您认为我需要发布此处运行的方法,请告诉我,但我认为问题出在服务器端。
奖金问题:我也想知道我是否在正确的轨道上。游戏相当复杂,但我只是打算使用 Gson 来序列化和反序列化对象,并根据来回发送的 gson 字符串委托适当的操作。在谷歌搜索服务器/客户端架构之后,我的方法似乎太简单了。我很难找到好的资源来学习更高级的服务器/客户端架构,所以任何指向优秀书籍或教程的链接都会有很大帮助。
谢谢大家!