既然要实现多线程服务器,那么我们就要从QTcpServer和QTcpSocket两个类继承出新的类来实现比较复杂的功能。现在来分析继承需要注意哪些问题。
首先,来看QTcpServer类。进入Qt Creator的帮助文档,可以看到QTcpServer类有几个重要的虚函数,不用说如果我们要继承QTcpServer类的话,有可能要重写这些虚函数。
virtual QTcpSocket * nextPendingConnection()这个函数的说明中有个Note需要注意一下:
Note: The returned QTcpSocket object cannot be used from another thread. If you want to use an incoming connection from another thread, you need to override incomingConnection().
简单的翻译来说就是:返回的qtcsocket对象不能从其他线程使用。如果要使用来自其他线程的传入连接,则需要重写incoming connection()。
这么说我们要继承QTcpServer类的话就要重写incoming connection()这个函数了。再来看看这个函数的说明。
This virtual function is called by QTcpServer when a new connection is available. The socketDescriptor argument is the native socket descriptor for the accepted connection.
The base implementation creates a QTcpSocket, sets the socket descriptor and then stores the QTcpSocket in an internal list of pending connections. Finally newConnection() is emitted.
Reimplement this function to alter the server's behavior when a connection is available.
If this server is using QNetworkProxy then the socketDescriptor may not be usable with native socket functions, and should only be used with QTcpSocket::setSocketDescriptor().
Note: If another socket is created in the reimplementation of this method, it needs to be added to the Pending Connections mechanism by calling addPendingConnection().
Note: If you want to handle an incoming connection as a new QTcpSocket object in another thread you have to pass the socketDescriptor to the other thread and create the QTcpSocket object there and use its setSocketDescriptor() method.
这么一大段说明简单来说就是:这个函数会创建一个socket并且发出newConnection()信号,如果要在线程中使用的话就要把socketDescriptor传递给创建的socket。
再来看QTcpSocket类。继承这个类,我们得知道客户端的IP地址和端口号吧,既然创建socket的时候要传进来一个socketDescriptor,那么这个东东我们也可以得到。
最后还有个函数要注意一下:int QTcpServer::maxPendingConnections() const,这里默认的最大连接数是30,显然这个也需要改变。