single Socket for listening and sending/receiving, Simultaneously?

This is a discussion on single Socket for listening and sending/receiving, Simultaneously? within the Networking/Device Communication forums, part of the General Programming Boards category; Hi,
Is it possible to use the same network Socket simultaneously, for listening (for incoming connections) and communicating with a ...

single Socket for listening and sending/receiving, Simultaneously?

Hi,

Is it possible to use the same network Socket simultaneously, for listening (for incoming connections) and communicating with a non-connected client (using the sendto() and recvfrom() functions)? Or must I have two separate sockets, and if so must the separate sockets also be bound to separate network ports? Just for the info, I am using WinSock 2 API functions.

I think you need threads for this ...

I think threads would be the right solution. I made a two-person chat application not too long ago, that I haven't finished yet, and I had to use threads, to control both sending and receiving data. Try going to http://msdn.microsoft.com/library and searching for _beginthread() or _beginthreadex(). I just used a function called Server(), declared as 'void Server()', that accepted connections and listened for incoming data. For multi-connection support is jus a little more complicated, but not by means of threads. You just have to create an array of listening sockets. For example:

Code:

// These are global variables
SOCKET listening[10]; // Where ten is the maximum number of sockets that can be connected at once

I don't know if this is EXACTLY what you need, but I think it should help you.

Originally posted by Hammer How would you tell the difference between incoming data and a new connection request?

If it where possible, then the listening function would return when a connection is requested by another comp. And the incoming data would be returned from the receiving function. Although I don't know how it is handled on a low-level, it is probably up to the protocol used.

Thanks for the info SyntaxBubble, it's not really what I was looking for but still useful. May I ask if you used threads that always listened for connections or message-based notification?

I think this may be possible, but is strongly discouraged as you can run into all sorts of problems. It would be much better to use a completely seperate socket for listening whilst doing other i/o, and would make your code more readable & understandable.

If you mean that in order to get more than 1 client to connect you need to create more listening sockets, I disagree. One listening socket can accept connections from any number of clients < the system's max number of sockets. If you mean that to get clients connecting on more than 1 port you need more listening sockets, I agree.