PDA

View Full Version : How to destroy a UdpSocket completely



ms20020048
21st October 2006, 05:34
I create a UdpSocket and work well, then destroy it.
However, when i create it again, my program does not work.
Please give me some advice.


void GPSNetwork::startReceive()
{
stop = false;
udpSocketRead = new QUdpSocket();
udpSocketRead->bind(45454);
connect(udpSocketRead, SIGNAL(readyRead()),this, SLOT(start()));
}

void GPSNetwork::run()
{
while ((udpSocketRead->hasPendingDatagrams())&&(stop==false))
{
QByteArray datagram;
datagram.resize(udpSocketRead->pendingDatagramSize());
udpSocketRead->readDatagram(datagram.data(),datagram.size());
if (datagram.size()!=0)
emit msg(datagram.data());
}
}

void GPSNetwork::stopReceiveFromNetwork()
{
stop=true;
disconnect(udpSocketRead, 0,this,0);
delete udpSocketRead;
}

wysota
21st October 2006, 09:18
My guess is that the operating system prevents you from binding to a port you just closed. Either don't bind the socket or set proper options to the socket (SO_REUSE if I remember correctly).

yuriy
23rd October 2006, 20:01
How about allowing reuse of the socket descriptor? In GPSNetwork::startReceive()

udpSocketRead = new QUdpSocket();
// get socket descriptor from the socket
int fd = udpSocketRead->socketDescriptor();

// allow multiple sockets to use the same PORT number
unsigned int yes=1;
if (setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) < 0)
{
perror("Reusing ADDR failed");
exit(1);
}
// then bind etc

Yuriy