Reputation: 51
I have created a simple server that currently uses a TCP socket for all my packeting needs. If some data transfer is best used with TCP and others with UDP, what is the most effective way to use them in tandem? Can you simply have 2 sockets? I cannot find example code that shows best practices for this, and it seems like something that would be difficult to debug if done improperly. Thanks!
Upvotes: 2
Views: 1443
Reputation: 12357
There is nothing to prevent you from having 2 listening sockets, one each for TCP and UDP. However, the communication method is generally chosen in advance for a given application. For example, the syslog
protocol is almost always implemented only with UDP. HTTP on the other hand is pretty much always implemented only over TCP. There are a few protocols that often support both (NTP, DNS are examples).
It would be extremely rare to find a single application that allows a single logical data stream to use both at the same time, and it would be nigh on impossible to ever get that working reliably.
But otherwise if you do support both mechanisms, debugging is straightforward because each can be treated and debugged in isolation.
TCP is far easier to use if you require reliable sequenced delivery -- and for most applications the obvious choice. Every byte sent via TCP is guaranteed to be delivered in the order you send it (or you will receive a distinct error notification), and the peer operating systems between the two machines will cooperate in attempting retries as needed in case any packets are dropped en route. A lot of stuff you don't need to worry about here. Downsides are: (a) some increased overhead, and (b) "message" boundaries are not respected (that is, TCP delivers a stream of bytes; the receiver won't necessarily get them in the same discrete chunks in which they were sent so you must impose message boundaries yourself).
UDP doesn't guarantee delivery. That is, packets may still be dropped, but with no notice to the sender and it is your (i.e. your application's) responsibility to handle that appropriately. Likewise, it is possible for packets to show up in a different order than you sent them (due to different routing paths, for example). On the other hand, the packet you send is the packet you receive so your message boundaries remain intact.
So UDP is often chosen for short "one-shot" or single message notifications, where it's easy to set a timeout at application level, or where each message stands alone and a lost message is non-critical. While TCP is usually the better choice when there is a long-lasting connection or large continuous data streams need to be sent (file transfers and so forth).
Upvotes: 2
Reputation: 3225
Unless you use a raw socket, you must have two separate sockets for UDP and TCP communication.
SOCK_STREAM
is for TCP and SOCK_DGRAM
is for UDP. SOCK_STREAM
and SOCK_DGRAM
.Upvotes: 1