简体   繁体   English

在Java游戏中使用TCP和UDP

[英]Using TCP and UDP for java game

I am making a real-time java game for my friends to play on LAN. 我正在为我的朋友制作一个实时Java游戏,以便他们在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). 该游戏在客户端-服务器体系结构中运行,并且目前正在使用UDP进行所有操作(用于位置更新和加入游戏)。 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). 当我与朋友通过Internet测试游戏时,丢失了一些重要的UDP数据包(例如用于生成敌人的数据包)。

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. ? 是否可以将UDP用于必要的更新数据包,以及将TCP用于诸如登录,断开连接,聊天等数据包? Can i use both protocol on the same port and socket? 我可以在同一端口和套接字上使用这两种协议吗?

Your best bet is just to use TCP. 最好的选择就是使用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. 除了为您提供重新发送功能外,您无需自己编写它们,也无需编写主机即可获得其他良好功能,TCP还将使处理路由器和防火墙变得更加容易。

I do recommend turning off the Nagle algorithm so data is always sent immediately. 我确实建议关闭Nagle算法,以便始终立即发送数据。

有时可能需要可靠的数据,有时需要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. 如果您有任何实时方面的知识,请不要在游戏中使用TCP。 You will regret it at some point down the road. 您会在以后的某个时候后悔。

What you want is to implement reliability/connections over UDP. 您想要的是通过UDP实现可靠性/连接。 Gaffer on Games have an excellent series on this topic. Gaffer on Games在这个主题上有出色的系列。 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/ 这是描述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 而且您很幸运-他们甚至在开放源代码库<3 https://github.com/networkprotocol/yojimbo中实现了所有这些功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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