简体   繁体   中英

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). Any pointers on what could be going wrong?

Here's my code for my 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.

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.

I'm wondering why you're reading serialized objects from the Socket, but writing out data using a PrintWriter. I would suggest using the ObjectOutputStream and being consistent.

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. This would allow you to write / read objects only using what's really necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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