Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I'm currently working on a c# online multiplayer game in real-time. The aim is to have client/server based connection using the UDP protocol. So far I've used UDP for players' movements and TCP for events (a player shooting, a player losing life) because I need to be sure such data will arrive to all players connected to the server. I know that UDP is said 'unreliable' and some packets may be lost. But I've read everywhere to never mix TCP and UDP because it can affect the connection.
The main question is how should I organize my network?
UDP is connectionless, how should I save who's is who? Should I save ip adresses of the clients in a list?
Should I use TCP for important events or use UDP? If I need to use UDP, how can I make sure that data will not be lost?
By using both TCP and UDP, I need to save for each player their IP in a list (for UDP) and the TcpClient which is connected in another list (for the UDP). How could I change that to be more effective?
Connections have improved a lot since early game development. In the past the speed advantages of UDP made it a very desirable protocol, even balanced out the reliability issues. However as networks have improved the reasons to shy away from TCP have dissipated.
I would advise picking one of the two protocols and going with it. But mostly because it will simply your network layer and make it easier to debug network issues. When I have to pick between TCP and UDP I make the decision more on how I want my networking logic to flow.
With a UDP based system you do need to do a bit more bookkeeping yourself, but not really enough for it to factor into the decision. A UDP game flows more like independent cells that all happen to share the same world. You don't want a lot of reactive logic (after he does this, i do that), if something is dropped or forgotten the game will keep going smoothly.
TCP will give you much more control. Depending on the API and can involve a bit more setup but its worth the effort. TCP lets you work with a networked partner much like you would work with another thread on the same CPU. There is an overhead with everything that you do but it sounds like you already have it working so might as well stick with it.
I generally tend towards UDP myself because its ingrained I think. Also whenever dealing with networking you have to plan for the un-expected, the lost or delayed packet, and UDP helps drive that message home. If you break that rule you will notice right away with UDP, might not with TCP.
Related
What I seek
I would like to know if anyone knows about efforts trying to make an connection oriented layer upon UDP in .Net. This would ease my work as I would not have to invent this all over again as I need to ensure the benefits of an network oriented connection (e.g. loss and order of received packets.)
Background
I want direct communication between devices behind NATs.
Due to constraints with TCP, Hole Punching and NAT, I think I need to use UDP as the protocol for communicating between the devices (e.g. silverlight 4 apps or mobile devices). I made the hole UDP hole punching work, so based on this I have decided to go on with a UDP-solution.
What you are looking for is called Reliable UDP. One implementation is here, I'm sure there are many more out there. Use google and pick the one you like best.
I very confuse about Synchronous and Asynchronous Socket in C#, i want develop a game play on LAN network, but i confuse which one is better for my application Hangman game.
This game can play with 1player mode or 2 players mode.
In 1 player mode just a player interact with serer
But 2 players mode 2 players interact with server by turn base. It mean if player A guess wrong word, he lose his turn and player B take this turn.
Can you give me suggest about Synchornous and Asynchronous.
Beside that how can client can find server if client dont need enter server ip? it mean what should i choose between TCP and UDP
and last question is can i create a server is asynchronous but clients are synchronous, is it ok?
Thank You Very much
The important part of about choosing Asynchronous vs Synchronous is how you make the communications interact with your GUI thread. Don't let a synchronous socket block your UI. I see the article here gives an idea what to expect and gives some guidance about using Asynchronous with Windows programming.
Winsock tips
Your second question about TCP/UDP there are a lot of difference between the two you should be aware of. First and foremost, TCP is going to guaranteed packet delivery while the connection is valid. Given your situation and the simple requirements and lack of performance needs. TCP is probably your best choice. If you are designing a high performance game where you have to allow for dropped packets and handle latency better, UDP becomes a better option but then you have to take into consideration what happens when you drop packets and have things like Out of Order packets. TCP hides all of that complexity from you and will make working with it simpler.
Mixing synchronous and Asynchronous client/server should cause not problems. They only know about the communication link itself (TCP/UDP).
so regarding your questions :
Can you give me suggest about Synchornous and Asynchronous: In your case given the complexity of the application you can use either sync or async sockets, as twilson stated the sync sockets blocks your main thread while the async ones don't so if you have performance issues go for the asynchronous sockets
Beside that how can client can find server if client dont need enter server ip? it mean what should i choose between TCP and UDP: well there's a fair difference between TCP and UDP connections, you usually use UDP (connectionless) when you have peformance issues like Voip apps, real time games,video chat and so on, while in onther cases you use TCP, so in your case TCP should suit you good.
and last question is can i create a server is asynchronous but clients are synchronous, is it ok?
Yes you could use this kind of implementantion even if it.s a good practice to have the same type of socket on both clients and server.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have a turn-based game in which two players may play against each others.
It's written in C# and uses XNA 4.0.
Currently multiplayer is implemented with TCP/IP. It works pretty nicely, but only if the players are within the same network and one of them knows the IP of the other.
So the question is: How should I implemented the online play for this game? Is TCP a reasonable method for connecting two random players from the opposite sides of the world without them having to deal with IP addresses and ports(or any other such technical details)?
To make this problem more challenging, I have no server for hosting the game matching service. (Well, I have an access to a virtual web server which I could use for sharing the IPs.)
To list questions:
Does .NET offer better choice of communication method than TCP?
What would be the best way to deal with NATs in my case?
Is there a cheap way of getting my own server and run the TCP game matching service there?
TCP vs UDP.
TCP is a bit slower than UDP but more failsafe.
Since your game is turn based it will probably send minimal amounts of data between the client and server and it is not really latency dependant, I would say you might aswell go for TCP.
To make this problem more challenging, I have no server for hosting the game matching service. (Well, I have an access to a virtual web server which I could use for sharing the IPs.)
If you are going to provide your players with a server browser or similar you will need to have a centralized server, a web server with a script/application built for this would do just fine.
Is there a cheap way of getting my own server and run the TCP game matching service there?
A web server or similar host would do just fine and is usually cheap, what you want is:
Function for a server to add itself to the server list.
Function for a client to retrieve the servers on the list.
Doing web requests with C# is no problem at all, the requests could look something like:
http://www.example.com/addToServerList.php?name=MyEpicServer&ip=213.0.0.ABC (adds this server to the list)
http://www.example.com/getOnlineServers.php (returns list of all the servers)
You need to specify what kind of load and latency that is expected and tolerated.
General answer is:
For real time games - UDP.
For scrabble-like-games - TCP.
Use your server to share IP's as you said.
Minecraft uses TCP. It's good for traffic that must be transmitted and received AND can be queued a little.
UDP is a one way error checking. Only the receiving side check for error. This was needed with the older slow ethernet technology where a round trip to check packets is too slow.
TCP is a very reliable protocol with a handshake. So the sending side knows if the data is transmitted sucessfully. But due to the round trip, it puts a lot more overhead and lag on the transmission.
TCP also do arrange packets, which UDP also don't do.
Some games it does not mind losing packets (for example "steaming" data where objects moves around, and it will get updated the next round of packet anyway). There you can use UDP. But if it is critical to get all the data, rather go with TCP, otherwise you will spend a lot of time writing code to make sure that all the data is transmitted successfully.
The networks is quickly enough and the internet being TCP/IP I recommend TCP, except if you really need very low lattency traffic.
This website gives a good summary:
http://www.diffen.com/difference/TCP_vs_UDP
NAT: Should not be a problem just as long as your Time To Live (TTL) is big enough. Every time it get NAT, it's TTL get subtracted by one. When it is 0, it gets dropped
Suppose you were forced to use TCP sockets over UDP sockets (ie: something that Silverlight insists on). Would it be possible to create a multiplayer game that involves sending real time positional updates to up to say eight players so that each player could accurately see every other player in real time, even though UDP would be the better protocol to use? Given the option, would you wish to go as far as to select a different technology (ie: Java), simply to gain UDP support?
Thanks,
Nick
As long as a few milliseconds aren't important i see no reason to use UDP.
To receive UDP packets, you must have a public IP address.
To receive UDP packets, you need to be able to listen on a port. Not all frameworks in all environments can do this, often for security reasons and such.
As you describe Silverlight as a target platform, we can anticipate that this won't always be the case for your players.
Use TCP.
As an alternative to Silverlight, you might look at Haxe (or Flash).
(From the comments, there is mention of STUN and stuff; that's an interesting if difficult angle to pursue.)
It depends on how fast of real-time you are looking at. For example, if you try to make a space battle, and everyone is close, but moving at a high speed, then you may find that the milliseconds difference makes a difference, but, if you are doing something like an auto racing game then it won't make any difference, so TCP is fine.
So, try it, get some numbers and decide if it is acceptable.
The bigger problem will be the difference in bandwidth, so, if one person is playing over a really slow connection, and everyone else are on very fast connections, then that slower player will be a problem. You may need to scale the updates to the slowest connection, and you may find that TCP/UDP issues are not enough of a concern, as the difference in connection speeds are a far bigger problem.
So, test with various connection speeds, with differing numbers of users, each with their own connection speeds, and see if, as one user, the game is still enjoyable.
UPDATE
It is not bandwidth that will be the concern, but the latency, as was pointed out in a comment. I had picked the wrong term, as several people might be able to respond quickly and be closer to real-time, but one user may be much slower, perhaps on a congested network, slow computer, or whatever, but they may only send updates every 1000ms, whereas everyone else is doing it every 100ms.
Speed, optimization, and scalability are the typical comparisons between the Udp and Tcp protocols. Tcp touts reliability with the disadvantage of a little extra overhead, but speed is good to excellent. Once a Tcp socket is instanced, keeping the socket open requires some overhead. But compared to the oft described burdens of Udp, which protocol actually has more overhead?. I've also heard that there are scalability issues with Tcp...yet the Internet (Web pages/servers) runs on Tcp - so what is it about Tcp that inhibits scalability?
Okay...so Udp doesn't require that overhead of keeping a connection open. But, it requires that you write extra methods to ensure all of the packet gets there, hopefully in the order that you want it received. If a packet isn't received in full, then you have to tell the client or server to resend. And you also have to keep some sort of message collection for partial packets, rebuild the partial messages, and check for a complete message before the message can finally be processed. Not to mention if the second part of a message never makes it, you have to either say resend the entire thing, or resend the part we are missing, or whatever.
Basically, my questions are:
Why would I choose Udp over Tcp for a serious, high-performance server with the added "overhead" of message
checking and manual ACK versus the "overhead" of a continuous stream?
If Tcp is good enough for the likes of World of Warcraft, why isn't Tcp more widely accepted as the protocol to use for a game server?
Note: I am not opposed to implementing Udp options for a server. We are using C# on .Net 3.5 framework. So I would also be interested in the best practices for dealing with Udp burdens. I am also using the asynchronous methods at the socket level rather than using TcpListener, TcpClient, etc. etc.
Well, I would recommend reading up some more. There are plenty places to look at the pro's and con's of TCP vs. UDP and vice versa, here are a few:
What Are The Advantages Of Using TCP Over UDP?
When should I use UDP instead of TCP?
TCP and UDP
What are the advantages of UDP over TCP?
However, this link may interest you the most, as it is directly about networked game programming:
Gaffer on Games - UDP vs. TCP
If I were to quote something small:
The decision seems pretty clear then,
TCP does everything we want and its
super easy to use, while UDP is a huge
pain in the ass and we have to code
everything ourselves from scratch. So
obviously we just use TCP right?
Wrong.
Using TCP is the worst possible
mistake you can make when developing a
networked game! To understand why, you
need to see what TCP is actually doing
above IP to make everything look so
simple!
I still recommend doing your own research on the matter though, and make sure which of the protocols suits your needs at the end of the day. This being said, it does seem to be the case that majority of games use UDP for their data. Anything that updates the entire state continuously does not need the overhead of guaranteed packet delivery.
First, I'll just paraphrase Stevens from Unix Network Programming Section 22.4 "When to Use UDP instead of TCP":
He basically says the following:
UDP is the only option for broadcast / multicast - so you have to use it there.
UDP can be used for simple request / reply apps. But you have to add your own error detection meaning at least acks, timesouts and retransmission.
UDP should not be used for bulk data transfer ( file transfers ) since you would have to build in all the functionality arleady in TCP to make it work right.
UDP should be used for real time data where speed of delivery is most important and some data loss is not an issue such as real time sensor data, live multimedia streams, real time stock quotes, etc.
The answer to your first question is very dependent on your definition of "high-performance". If you're primary concern is low latency, i.e. the individual data packets / requests arriving as quickly as possible than UDP would be the way to go. There are two primary reasons for this. Assuming packets / requests are fairly independent of each other than using TCP would introduce a problem known as head-of-line blocking.
Let's say you send two independent packets / requests. First A then B. Since TCP is stream based, if A get's lost in the network and needs to be retransmitted then even if B has already successfully arrived it can't be delivered to the application by the stack until A arrives, introducing unnecessary latency. Not only that, but until A arrives, B can't be acknowledged by the stack which might cause B to also be retransmitted causing needless network congestion.
One way around this problem is to use separate connections for each request, however this also introduces latency and hogs system resources. UDP bypasses all these problems.
Another issue in high performance ( low latency ) servers is the Nagle Algorithm which can add significant latency in TCP communications.
The answer to your second question is that WoW probably sends streams of data, not independent request / reply pairs. Also, some of the latency of TCP can be removed by disabling the Nagle algorithm. If they do use some request / reply communications they may have simply made a design decision that reliability is more important to them than latency.
Define "serious high performance" - how many concurrent connections are you talking about and how much data is flowing?
Take a look at the answers to this question What do you use when you need reliable UDP? which list some of the reliable protocols that have already been built on UDP. You might find one that works for your situation, or you may at least find some useful ideas.
The key to using UDP effectively here is to have some level of reliability and some level of unreliability and you get more of an advantage the more each datagram is able to be handled independently of others. The advantage over TCP is that you get to act on each datagram and decide if you can use it as it arrives. This is why it works for action games.
So, IMHO, if you need 100% reliability AND in order delivery then go with TCP; don't try and reimplement TCP in UDP.
It's Reliability vs Performance.
FPS games don't require -all- the packets to reach the destination, to reach it in order, to be exceptionally big, or to assure big throughput. They only require the packets to reach the server AS SOON AS POSSIBLE. This is the ultimate priority and overhead of TCP is simply an unnecessary burden.
WoW, in its "not quite realtime" communication and often tons of data to transmit (in crowded areas), may have to deal with packets exceeding MTU (requiring fragmentation) and requires reliability (fewer bigger packets = packet lost hurts more). So its choice of TCP is logical. Same would go for most turn-based strategy games and the like. In games where the player with ping of 30ms beats the player with ping 50ms UDP is the king.
I think the biggest part of TCP/IP that inhibits scalability is that it maintains a buffer on all incoming / outgoing connections up to basically the size of the window. So if I have a high latency but high throughput client i'm talking to, I have to keep all sent packets in buffer until I receive an ack. So for a few connections this is fine, but for handling 100K connections, it can start to be problematic overhead. On the receiving end, if a packet is dropped, again it will buffer all new packets received until the one required is retransmitted.
If you're going to implement retransmission, you need to do the same thing, and hence will have the same overhead. However, UDP does give you an advantage, if you know the end-to-end link speeds, or if certain message can be delivered out of order, or certain messages don't need retransmission. Keeping the gaming scenario:
packet 1 = move to 1,1
packet 2 = shoot
packet 3 = move to 2,2
Most game designers, if packet 1 is lost, but packet 3 is received, packet 1 is no longer important because it contains out of date information anyways. However, you could opt to say packet 2 is important, so if it's not acked, send a retransmission.
If you need high throughput, and connect two servers directly with 1000Mbps ethernet, TCP/IP will take awhile to scale and have additional overhead, and will likely never achieve a true gigabit connection due to the congestion avoidance mechanisms. However, you know it's 1 Gbps, so you can set up you're UDP to transmit at up to a 1 Gbps (minus overhead) yourself.
To answer you're questions more directly:
If you are going to ack every packet anyways, there isn't a massive benefit to having UDP, other than you can process some messages while waiting for retransmission (unless you want in-order delivery as well).
Udp isn't considered for game servers as much, mainly out of the scenario above, and real time combat systems such as First person shooters, where a message can be dropped, and the new message to come will invalidate the dropped message anyways. World of warcraft can get away with using TCP, since they don't have to be as precise with timing, and likely have some good logic that makes it more difficult for you to tell the difference anyways. The combat system simply doesn't require the speed.
I'd also contend that some of the justification is holdover from years ago, when everyone had less-reliable, and slower Internet connections. TCP is also more lenient for sharing the network, so if there's a lot going on, it will slow down so everyone gets a share of the connection (congestion avoidance).
TCP/IP is a protocol designed by people far smarter than I over years of research. Tuning in the last several years has allowed it to perform better with the faster and faster average network speeds we are seeing, and doesn't require a great understanding to use.
However, replacing this with UDP, does require a significant understanding of networking. I've seen badly written UDP programs saturate 1Gbps links and kill all traffic on the link, because they implemented a rather naive retransmission algorithm.
Here's a list of things TCP/IP can now do that you'd loose by going UDP:
- In order arrival to you're program
- retransmission (Now with Fast retransmit, selective acknowledgement, and other features)
- Maximum segment size
- Path MTU Discovery
- Black Hole Detection (extension of Path MTU)
- Congestion avoidance
Because of this, I'd highly recommend sticking with TCP/IP if it suits you're needs.
Also not to nit pick, but you're comment about the Internet running on TCP/IP is wrong, there are in fact dozens of Internet routeable protocols check them out here. I think you were referring to web pages and web servers are all running on top of TCP/IP. Which again for the web is great where us humans won't notice a delay as long as the page shows up correctly. Even for TCP/IP, their is some challenge that TCP/IP isn't aggressive enough for the web: Google thinks tcp/ip should be more aggressive by default