赞
踩
TCP服务器的代码实现比UDP略为复杂一点,因为TCP的服务端需要生成与管理一个额外的QTcpServer对象。为了支持多线程,用moveToThread方法把服务器放在一个单独的线程中。
用MyTcpServer类实现TCPserver,供主程序调用方法。
MyTcpServer类头文件内容如下:
//MyTcpServer.h # include <QObject> #include <QTcpServer> #include <QTcpSocket> #include <QThread> #include <QDebug> class MyTcpServer : public QObject { Q_OBJECT public: explicit MyTcpServer(QObject *parent = 0); ~MyTcpServer(); signals: void dataArrive(QByteArray ba); //send data to deal public slots: void onNewConnection(); //new connection come void socketReaddata(); //read socket data private: QTcpServer *m_tcpserver; QTcpSocket *m_socket; QByteArray tmpdata; QThread *m_thread; int tcpPort = 6000; QByteArray m_buffer; }
MyTcpServer类的源文件如下:
//MyTcpServer.cpp MyTcpServer::MyTcpServer(QObject *parent) : QObject(parent) { m_thread = new QThread(); m_tcpserver = new QTcpServer(); connect(m_tcpserver, &QTcpServer::newConnection, this, &MyTcpServer::onNewConnection, Qt::DirectConnection); if (!m_tcpserver->listen(QHostAddress::AnyIPv4, 6000) { m_tcpserver->close(); qDebug()<< "tcplistenerror:" << m_tcpserver->errorString(); } this->moveToThread(m_thread); m_tcpserver->moveToThread(m_thread); m_thread->start(); } MyTcpServer::~MyTcpServer() { m_thread->quit(); m_thread->wait(); delete m_thread; m_tcpserver->close(); delete m_tcpserver; } void MyTcpServer::onNewConnection() { QTcpSocket *socket_temp = m_tcpserver->nextPendingConnection(); m_socket = socket_temp; qDebug() << "new TCPconnection come."; connect(socket_temp, SIGNAL(readyRead()), this, SLOT(socketReaddata())); connect(socket_temp, SIGNAL(disconnected()), this, SLOT(socketDisconnect())); } //读取info,发送给类外的接收槽处理 void MyTcpServer::socketReaddata() { if (m_socket->bytesAvailable() <= 0 { return; } m_buffer = m_socket->readAll(); tmpdata.clear(); tmpdata = m_buffer.left(20); m_buffer.remove(0, 20); emit dataArrive(tmpdata); } void MyTcpServer::socketDisconnect() { m_socket->deleteLater(); }
文中的TCP服务器业务逻辑很简单,监听端口号6000,每收到数据取头20个字节并发送,复杂的逻辑可以改写socketReaddata函数。
在工程的pro文件中不要忘记把network模块加入进来。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。