简体   繁体   中英

Using TCP and UDP for java game

I am making a real-time java game for my friends to play on LAN. The game is working in a client-server architecture, and it is using UDP for everything right now (for both position updates and joining to the game). When I tested the game with my friend over the Internet, a few important UDP packets were lost (like the one that is for spawning enemy).

So my question is, what is the best solution for making real-time multiplayer games, work? Can I use UDP for the necesarry update packets and TCP for packets like log-in, disconnect, chat etc. ? Can i use both protocol on the same port and socket?

Your best bet is just to use TCP. In addition to providing the resend capabilities for you, so you won't have to write them yourself, along with a host off other good features, TCP will also make it a lot easier to deal with routers and firewalls.

I do recommend turning off the Nagle algorithm so data is always sent immediately.

有时可能需要可靠的数据,有时需要TCp。有时不需要它,以便您可以使用UDP。合并两者。

Just want to help any passers by that stumble on the incredible bad advice given in the other answers. Sorry, I am sure it is well meaning. Do NOT use TCP in games if you have any kind of realtime aspect to it. You will regret it at some point down the road.

What you want is to implement reliability/connections over UDP. Gaffer on Games have an excellent series on this topic. I cordially recommend everyone interested in this topic to read the whole series. Here's a link to the post describing "connections" over UDP: https://gafferongames.com/post/virtual_connection_over_udp/

And you're in luck - they even implemented all of this in an open source library <3 https://github.com/networkprotocol/yojimbo

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