Realization of QTcpServer
Today, I want to know about the QtNetwork Module. What will be the beginning of this module? Let’s try it from the TCP protocol. I think the QTcpServer will be OK. So, here we go.
As we know from the qt document, we always use the listen () function to listen the appointed port, and wait for the coming connection. So the first thing is to see this function.
Q_D(QTcpServer);
if (d->state == QAbstractSocket::ListeningState) {
qWarning("QTcpServer::listen() called when already listening");
return false;
}
QAbstractSocket::NetworkLayerProtocol proto = address.protocol();
First, we get the point of QTcpServer Object by the Q_D macro.And then to determine the protocol type which is IPV4 or IPV6.
#ifdef QT_NO_NETWORKPROXY
static const QNetworkProxy &proxy = *(QNetworkProxy *)0;
#else
QNetworkProxy proxy = d->resolveProxy(address, port);
#endif
Here to set the proxy if the QT_NO_NETWORKPROXY is not defined. The detail analyzes will in recent days.
delete d->socketEngine;
d->socketEngine = QAbstractSocketEngine::createSocketEngine(QAbstractSocket::TcpSocket, proxy, this);
if (!d->socketEngine) {
d->serverSocketError = QAbstractSocket::UnsupportedSocketOperationError;
d->serverSocketErrorString = tr("Operation on socket is not supported");
return false;
}
if (!d->socketEngine->initialize(QAbstractSocket::TcpSocket, proto)) {
d->serverSocketError = d->socketEngine->error();
d->serverSocketErrorString = d->socketEngine->errorString();
return false;
}
Those codes are about the socket engine.
Here is something about listening port of UNIX system.
#if defined(Q_OS_UNIX)
// Under Unix, we want to be able to bind to the port, even if a socket on
// the same address-port is in TIME_WAIT. Under Windows this is possible
// anyway -- furthermore, the meaning of reusable on Windows is different:
// it means that you can use the same address-port for multiple listening
// sockets.
// Don't abort though if we can't set that option. For example the socks
// engine doesn't support that option, but that shouldn't prevent us from
// trying to bind/listen.
d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
#endif
Then, they try to bind and listen the address and port.
if (!d->socketEngine->bind(address, port)) {
d->serverSocketError = d->socketEngine->error();
d->serverSocketErrorString = d->socketEngine->errorString();
return false;
}
if (!d->socketEngine->listen()) {
d->serverSocketError = d->socketEngine->error();
d->serverSocketErrorString = d->socketEngine->errorString();
return false;
}
After this, set some property to the object of QTcpServer. In this function, the QAbstractSocketEngine class is often used. So let’s see it from closer.
In the network/socket folder, we can find three kind of socket engine. They are QNativeSocketEnginePrivate, QNativeSocketEnginePrivate and QSocks5SocketEnginePrivate classes.
It’s time for me to go to sleep. The next day, I will get up early for the new classes.
November 15, 2009 23:06