2

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

4 Comments

-1 for advising not to use UDP at all and for multithreading recommendation (why not just use something like select?) -- maybe you should just remove the second paragraph. :-p
To an extent he's right-- we are required to multithread this. I'm just not worrying about that yet.
But we're also required to use UDP. No choice there.
UDP is used for less important information. I was responding in relevance to the topic. Chat servers should not necessarily be using UDP connections, in my opinion. More info on TCP and UDP Here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.