渡世白玉 |
2013-09-18 18:02 |
QtTcpServer多线程实现,更新,线程可控
参考: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
|
|