• C

Reading from the same port twice

Hi,

I have an application where I would like to create two threads and inside the two threads create socket in each and listen on the same port number for UDP PDUs being sent through. What I would like to know is - is it possible to do this, ie can one receive PDU's from the same port twice? At the moment I am having trouble binding the socket on the same port number.

Cheers

Mat
pinmj001Asked:
Who is Participating?
 
grg99Connect With a Mentor Commented:
This is a standard server-side setup.   The best way to do it is as jamie mentioned:

(1)  You have one thread that just loops, waiting for and reading UDP packets.  Whenever it gets a packet it spins off a worker thread to handle that packet and loops back again to waiting for a packet.

(2)  If you need higher performance, you can have a "pool" of spun-off worker threads that are pre-started, and they wait for the main thread to send them a packet to handle.  Then once the worker thread has handled the packet, it can do one of two things:

(1)  It can loop back and wait again for another packet from the main thread.  This requires that you're sure the worker thread cleans up after handling the first packet, and is in a good state to handle another one.

(2)  The worker thread could exit, then the main server could spin off another worker thread.

Note that you have to be really careful to use proper semaphore techniques to signal between the main thread and workers.  It can take quite a while to debug these complex interactions.

0
 
Jaime OlivaresConnect With a Mentor Software ArchitectCommented:
I have faced this problem many times. In principle, it is not possible, even more in a portable way.
The solution, create a listening thread, and pass frames to both processing threads, or 3, or 4, in fact I do this with 7-10 threads.
0
 
pinmj001Author Commented:
Thanks for the input guys.

I think I have solved the problem with this: setsockopt(RecvSocket,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes) which allows a new socket to bind on an address and port already in use by an existing socket.

Cheers

Mat
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.