使用QTcpServer创建一个简单的服务器程序之二:多线程服务器(1)-继承分析

既然要实现多线程服务器,那么我们就要从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,显然这个也需要改变。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值