The problem is choosing the ports. As far as I know, you cannot find and reserve a free port without binding to it. So I bind 2 ports. Now I know what ports I can use. Both components need to know both ports in order to send and receive, though they only each really need to bind to the one they receive on. Unfortunately, after the first component binds 2 sockets and tells the second component what ports to use, the second component can't bind to the port it needs (since the first Component is still bound to it).
The preferred solution would be for Component 1 to be able to be able to reserve an open port for Component 2. Perhaps by binding but allowing a second socket on the same port to be bound. Or throwing the socket object across the thread boundary somehow.
I would love if this code printed "Success". (Using Qt 4.5)
void theProblem()
{
QHostAddress udpHost("localhost");
quint16 port = 0;
QUdpSocket socket;
socket.bind(udpHost, port);
createSocketInNewThread(udpHost, socket.localPort());
sendMessageToSocketInNewThread(udpHost, socket.localPort());
}
void createSocketInNewThread(const QHostAddress& udpHost, int port)
{
// Pretend we're in a new thread.
QUdpSocket secondSocket;
bool successfullyBound = secondSocket.bind(udpHost, port);
qDebug("%s", successfullyBound?"Success":"Failure");
}