Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

tcp - Java Server - Sending packets out incorrectly?

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?


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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...