temporary_user_name
temporary_user_name

Reputation: 37018

Accepting both TCP and UDP connections?

I'm creating a chat server which accepts both TCP and UDP connections. Assume for now that the server only allows a single client to connect; there's nobody to chat with yet.

But how do I do that?

 int sock = socket( PF_INET, SOCK_STREAM, 0 );

As I understand it, the essential difference in setup is this--

 int sock = socket( PF_INET, SOCK_DGRAM, 0 );

But how do I do both simultaneously? Set up two ports and alternate listening on both for connections?

Upvotes: 2

Views: 1378

Answers (2)

Anthony
Anthony

Reputation: 496

TCP and UDP are two different things. TCP makes sure that data is sent, and it guarantees delivery. However, UDP does not offer this feature. Because they are different and data is received differently, two ServerSockets must be set up. One to handle TCP connections, and the other to handle UDP connections.

My advice is not to use UDP when sending important information, for it's unreliable and DOES NOT guarantee the delivery of the data you wish to send. However, if it is absolutely necessary to use both TCP and UDP protocols, then I suggest multithreading the server, so that it listens for both types of connections, and accepts them both.

Note: Have you noticed that websites can start with http:// and https:// ? The destination is the same, but the type of data sent is different, and a different port number is used (80 for http, and 443 for https). This is just a quick explanation as to why you'll need the server to host on two different ports.

Upvotes: -1

Art Swri
Art Swri

Reputation: 2804

Have a look at the select() function. It allows 'watching' multiple file descriptors. Hint: UDP does not have connections, so you don't have a 'listener' socket. For TCP, you open a listener socket, on which connections can be accepted. You can use select() to watch the 'listen' socket.

Upvotes: 2

Related Questions