问题
i am trying to write udp chat server in c language. i have written tcp chat server before and it is ok.
in tcp server, accept function returns an fd number and server communicate with a specific client according to this fd number.
but in udp, how can i listen a specific client?
In my tcp server, after a client connect to server, a thread is created and it listen this client. So for each client, there is a thread that listen to according to fd number that is returned from accept function. so any message can send according to this fd number to specific client.
How can i achieve this in udp server?
Thanks for answers.
回答1:
You use recvfrom
to find out the source IP/port and then reply with sendto
. You only need to bind
to select a server port. You don't accept
. All connect
does for UDP is set the default destination (which you plan to override with sendto
).
回答2:
It's preety simple. As you know the UDP is connectionless, it may share the same port.So the idea is here.Just create thread for every client.It will be great if you have more CPU core.you can use every core for particular number of clients.(It can be done by map)Now when the same client knock again just send him to that thread and core.So if you have 1...n core you have to create n thread with setting cpu to every thread.
I have done an experiment with 8 core server in that way and its worked fine.
I will give that code on my blog in some days later after cheacking it to gigabit switch.. :)
matrixsust.blogspot.com
Hope it helps.
回答3:
Just create a UDP socket and call connect(). But you don't want to do that. The whole joy of UDP servers is that they only need one socket. Have a think about it. You only need the thread in TCP because you are forced to have a dedicated socket, and a dedicated thread is the easiest (and not the only) way of handling it. In UDP you can jst keep reading from the same socket, and the source address tells you which client each diagram is from.
回答4:
i used recvfrom and sendto function. Firstly client sends message to server by sendto. and server takes message by recvfrom. In recvfrom i take address of client by sockaddr_in struct. After i can not achive bind this and use sendto
来源:https://stackoverflow.com/questions/4199088/udp-chat-server-in-c