Dennis
Dennis

Reputation: 3

What would be better in Java for networking? UDP or TCP?

What should be used for a mmo game in java. UDP or TCP? And why? TCP is a point-to-point relationship and carries every packet through while UDP has no point-to-point relationship and can drop off packets resulting in lag. Which one is the better one to use in this scenario?

Upvotes: 0

Views: 813

Answers (5)

iluxa
iluxa

Reputation: 6969

My experience with UDP and TCP is like this:

  • UDP is significantly faster. we're talking 2 orders of magnitude.
  • On wired networks, UDP packet loss is less than 1%
  • On wireless, UDP packet loss can easily reach 80%, and the physical distance to the router matters: you'll lose 20% of packets from a foot away and 50% from 20 feet away.

So UDP is good for non-essential stuff. For example, if 2 dudes are running around in your game, and Player A receives Player B's current coordinates and velocity over UDP every 100 millis, Player A can extrapolate for a while without going too far off. If on the other hand Player A has a full house, and Player B got a royal flush, the situation is different.

In my project, I used UDP as the primary communication scheme, with every receiver sending back a notification. If communication failed for longer than X though, I resorted to TCP.

Upvotes: 0

Alain Pannetier
Alain Pannetier

Reputation: 9514

The question is not really linked to Java. UDP datagrams are not guaranteed to reach the destination, TCP datagrams are. Consecutive UDP datagrams can also reach their destinations out of order. For instance DNS is based on UDP because requests and responses just take one datagram. If you need reliability and do not want to implement retries. TCP is your choice. Nowadays, the computing overhead is minimal, so that I don't think there is much performance gain to expect from favouring UDP.

Upvotes: 0

biziclop
biziclop

Reputation: 49804

It doesn't matter if it's Java or not, TCP and UDP have the same advantages and drawbacks that are independent of the language.

But more often than not it boils down to one basic design question: when a packet is dropped, what should happen?

  1. Pretend it never happened. This is UDP territory.
  2. Wait until the packet is resent. This is where TCP should be used.

Neither approach is right or wrong in itself, both will cause problems in your game, but this is the question you should answer first.

Upvotes: 2

Alnitak
Alnitak

Reputation: 340055

The answer depends not on the language, but on the requirements of the game.

If your game can cope with status updates from players (or the server) either going missing, or arriving out of order, then UDP should be fine.

If you need real-time response with minimal latency (and the above issues are solved) then you should also UDP.

Otherwise, you should use TCP.

Upvotes: 3

ldx
ldx

Reputation: 4084

See this question:

Android game UDP / TCP?

Upvotes: 1

Related Questions