我对线程世界有点陌生,我正在制作一个游戏服务器,分配每个连接到另一个线程的客户端,这样我就可以在同一个端口上接受多个客户端。但是,我在客户端连接到服务器时遇到问题,但无法发送数据(以 ObjectOutputStream 的格式发送到服务器)。关于可能出错的任何指示?
这是我的 MatchmakingServer.java 的代码
try {
listenForPlayers = new ServerSocket(portNumber);
System.out.println("Port opened. Searching for players");
while (true){
Socket clientSocket = listenForPlayers.accept();
Runnable r = new PlayerHandlerForServer(clientSocket);
new Thread(r).start();
}
} catch (Exception e) { }
我的 PlayerHandler 对象实现了 Runnable,这是它的 run 方法。
private Player player;
private ObjectInputStream getPlayerData;
private static PrintWriter sendPlayerData;
private Socket socket;
public void run() {
try {
getPlayerData = new ObjectInputStream(socket.getInputStream());
player = (Player) getPlayerData.readObject();
//do stuff with the player object, this code get executed.
sendPlayerData = new PrintWriter(socket.getOutputStream(),true);
updatePlayersFound(sendPlayerData);
} catch (Exception e) { }
}