• 12817阅读
  • 6回复

QtTcpServer多线程实现,更新,线程可控 [复制链接]

上一主题 下一主题
离线渡世白玉
 

只看楼主 倒序阅读 楼主  发表于: 2013-09-18
参考:http://www.qtcn.org/bbs/read-htm-tid-54890.html
移除其十六进制的发送和接受。

更新内容:添加线程管理类,可以固定线程,或者固定每个线程处理的连接数、、、、、

继承自QTcpServer,希望多线程处理Qtcpsocket。
代码基于Qt5和C++11,建议win下用mingw版Qt。
代码中的信号曹大多用Qt5的新语法,以便使用lambda表达式,
所以有很多lambda表达式的应用。
里面有大量的qDebug() <<“*”<<QThread::currentThreadId();语句,以便观察线程状态,
实际应用请注释掉。一些只是的测试代码,


实现时分别继承QTcpServer和QTcpScoket实现出自己需要的类。
继承QTcpServer为每个客户端连接时分配线程,并接受处理tcpScoket的信号和槽、、还有发送信息,储存连接信息等。
继承QTcpScoket为处理通信数据和增加信号的参数,以便和tcpServer更好的配合。
首先是继承并重写QTcpServer的incomingConnection函数去自己实现tcpsocket连接的建立和分配。
其文档的默认描述为:
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 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.
译文(谷歌翻译和自己简单的更正):
当QTcpServer有一个新的连接时这个虚函数被调用。该socketDescriptor参数是用于接受连接的本地套接字描述符。
该函数会创建一个QTcpSocket,并设置套接字描述符为socketDescriptor,然后存储QTcpSocket在挂起连接的内部清单。最后newConnection()被发射。
重新实现这个函数来改变服务器的行为,当一个连接可用。
如果该服务器使用QNetworkProxy那么socketDescriptor可能无法与原生socket函数使用,并且只能用QTcpSocket:: setSocketDescriptor()中使用。
注意:如果你想处理在另一个线程一个新的QTcpSocket对象传入连接,您必须将socketDescriptor传递给其他线程,并创建了QTcpSocket对象存在并使用其setSocketDescriptor()方法。
所以我们必须先重写这个函数:

代码地址:https://github.com/dushibaiyu/QtTcpThreadServer


完全描述:http://www.dushibaiyu.com/2013/12/qtcpserver多线程实现.html

离线embeddedking

只看该作者 1楼 发表于: 2013-09-24
楼主威武啊,这些有点高深啊,小弟有个简单的Qt问题想请教下,不知道有空没?
离线渡世白玉

只看该作者 2楼 发表于: 2013-09-27
回 1楼(embeddedking) 的帖子
是参照大牛的丰富下、、、
离线chenjun0211

只看该作者 3楼 发表于: 2013-10-01
”继承QThread来处理QTcpSocket,只有Run()中的是在新的子线程中运行“ 这个问题你要仔细阅读Qt的文档或者csdn上面专门有说Qt多线程的处理,其中说的是只有run()为开启一个子线程,其他的类函数都是主线程中处理,所以你你的发送和接受等操作需要使用类实现后在run()中实例化那个处理类并exec()后所有的操作就会在新的线程中运行了
离线渡世白玉

只看该作者 4楼 发表于: 2014-01-18
添加线程管理类,可以固定线程,或者固定每个线程处理的连接数、、、、、
主线程只负责建立新连接和维护连接线程、、
每个Socket的处理都在各自的线程、、
4条评分好评度+1贡献值+1金钱+1威望+1
燕子飞时 好评度 +1 - 2019-09-26
燕子飞时 贡献值 +1 - 2019-09-26
燕子飞时 威望 +1 - 2019-09-26
燕子飞时 金钱 +1 - 2019-09-26
离线nigoole

只看该作者 5楼 发表于: 2014-02-17
有句话说得好:好好学习,天天向上。加油~~!有上船的朋友联系企鹅393320854
离线shijiegong

只看该作者 6楼 发表于: 2016-09-22
学习学习,多谢楼主!
快速回复
限100 字节
 
上一个 下一个