Details
-
Bug
-
Resolution: Done
-
P3: Somewhat important
-
4.5.2, 4.5.3, 4.6.0
-
None
-
-
I2f8d450bcfb8a7f3abd8918a4e789a850281dd13 (5.0) I2f8d450bcfb8a7f3abd8918a4e789a850281dd13 (4.8)
Description
QTcpServer::listen() returns true when someone is already listening on that same port - Mac OS X
- If I start the server two times, both servers report they have successfully bound the ports
When I send requests to the ports the following happens:
- Requests to port 1501 are processed by the first instance
- Requests to port 1502 are processed by the second instance
- If I stop the second instance, requests to port 1502 are also processed by the first instance
#include <QtCore/QCoreApplication> #ifndef SERVER_H #define SERVER_H #include <QObject> #include <QTcpServer> #include <QTcpSocket> #include <QCoreApplication> class Server : public QObject { Q_OBJECT public: Server() : QObject(0), p1(new QTcpServer(this)), p2(new QTcpServer(this)) {} void start() { if(p1->listen(QHostAddress("0.0.0.0"), 1501)) { qDebug() << "Bound port 1501"; connect(p1,SIGNAL(newConnection()), this, SLOT(handleConnection())); } if(p2->listen(QHostAddress("127.0.0.1"), 1502)) { qDebug() << "Bound port 1502"; connect(p2,SIGNAL(newConnection()), this, SLOT(handleConnection())); } } void stop() { QCoreApplication::quit(); } private slots: void handleConnection() { QTcpSocket* s = 0; if( sender() == p1 ) { s = p1->nextPendingConnection(); } else if( sender() == p2 ) { s = p2->nextPendingConnection(); } else { qWarning() << Q_FUNC_INFO << ": Unknown Sender"; if( p1->hasPendingConnections() ) s = p1->nextPendingConnection(); else if( p2->hasPendingConnections() ) s = p2->nextPendingConnection(); } if( s ) { qDebug() << "Incoming connection at " << s->localAddress().toString() << "-" << s->localPort() << " from " << s->peerAddress() << "-" << s->peerPort(); QByteArray data = s->readAll(); qDebug() << "Received: " << data; if( data == "STOP" ) stop(); s->write("OK"); s->close(); s->deleteLater(); } } private: QTcpServer* p1; QTcpServer* p2; }; #endif // SERVER_H #include "main.moc" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Server s; s.start(); return a.exec(); } // CODE END