简体   繁体   English

多线程服务器不接受客户端输出流

[英]Multithreaded server not accepting client outputstream

I'm kinda new to the world of threading, and I'm making a game server, assigning every client who connects to another thread so I can accept multiple clients on the same port. 我对线程世界有点陌生,我正在制作一个游戏服务器,分配连接到另一个线程的每个客户端,以便我可以在同一端口上接受多个客户端。 However, I'm having an issue with clients connecting to the server, but not being able to send data (in the format of an ObjectOutputStream to the server). 但是,客户端连接到服务器时遇到问题,但是无法发送数据(以ObjectOutputStream的格式发送到服务器)。 Any pointers on what could be going wrong? 关于可能出什么问题的任何指示?

Here's my code for my MatchmakingServer.java 这是我的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) { }

My PlayerHandler object implements Runnable and here's its run method. 我的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) { }

}

As pointed in the comments log the exceptions, they will provide a clue as to what might be causing this problem. 如注释日志中指出的那样,这些异常将提供有关可能导致此问题的线索。

A wild guess would be that your Player class does not implement the Serializable interface. 一个疯狂的猜测是您的Player类没有实现Serializable接口。

I'm wondering why you're reading serialized objects from the Socket, but writing out data using a PrintWriter. 我想知道为什么您要从Socket读取序列化的对象,却使用PrintWriter写入数据。 I would suggest using the ObjectOutputStream and being consistent. 我建议使用ObjectOutputStream并保持一致。

Sending serialized objects might be overkill. 发送序列化的对象可能会过大。 There could be more data being sent then you care about. 可能有更多的数据要发送,然后您才在乎。 This could cause useless network lag to your game clients! 这可能对您的游戏客户端造成无用的网络延迟! You might want to look at using DataInputStream / DataOutputStream. 您可能想看看使用DataInputStream / DataOutputStream。 This would allow you to write / read objects only using what's really necessary. 这将允许您仅使用真正必要的对象来编写/读取对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM