Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Currently have a TCP server built in Java and I'm sending messages/packets out to clients using their socket's OutputStream:

// Send all player's information to everyone else
outerPlayerIter = players.iterator();
while(outerPlayerIter.hasNext()) {
    Player outerPlayer = outerPlayerIter.next();
       
    Iterator<Player> innerPlayerIter = players.iterator();
    while(innerPlayerIter.hasNext()) {
        Player innerPlayer = innerPlayerIter.next();
        boolean isYou = false;
        if(innerPlayer.equals(outerPlayer)) isYou = true;
        // Send innerPlayer's info to outerPlayer
        Thread.sleep(100);
        dataBuffer.clearBuffer();
        dataBuffer.writeByte(Msgs.mm_toclient.MES_SENDPLAYERINFO);
        dataBuffer.writeBool(isYou);
        dataBuffer.writeBool(innerPlayer.getIsHost());
        dataBuffer.writeString(innerPlayer.getName());
        dataBuffer.writeString(innerPlayer.getPublicIP().getHostAddress());
        dataBuffer.writeShort((short)innerPlayer.getUdpPort());
        outerPlayer.getSocket().getOutputStream().write(dataBuffer.getByteArray());
        outerPlayer.getSocket().getOutputStream().flush();
    }
   
}

However, sometimes the clients don't appear to receive all the messages. I can't send multiple messages at the exact same time over one socket.

One way to temporarily fix this was to sleep before I send another packet out. But I'm not sure why this is needed.

Am I doing something wrong in regards to how I'm sending/writing the packets out to be sent? What can be fixed to allow multiple packets to be received correctly at once without sleeping?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
765 views
Welcome To Ask or Share your Answers For Others

1 Answer

It might be due to the fact that the client closes the socket way too fast before the communication should actually finished. Could you please try to bump up the thread.sleep value or, on the client side, if you use any kind of timing, try to bump up that one as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...