服务器
使用前要在cmake
工程文件里边添加network
模块
1 2 3
| find_package(Qt5 COMPONENTS core network REQUIRED)
target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Network)
|
TCP通信服务器的核心类是QTcpServer
,头文件同名
使用也特别简单,先绑定IP地址
和端口号
,listen的返回结果如果是false
则端口号有可能被占用,Windows上建议用netstat -aon | findstr "9090"
事先看一下端口占用情况,Linux下则是用netstat -tlp | grep 9090
1 2
| QTcpServer server; bool ret = server.listen(QHostAddress("127.0.0.1"), 9090);
|
编写newConnection
信号对应的槽函数,服务器通过nextPendingConnection
接口获取已建立的socket,然后对socket进行读写
1 2 3 4 5 6 7 8 9 10 11
| QObject::connect(&server, &QTcpServer::newConnection, [&]() { auto &&socket = server.nextPendingConnection(); auto timer = new QTimer(); QObject::connect(timer, &QTimer::timeout, [&, socket]() { socket->write(QByteArray("hello world")); }); timer->start(1000); QObject::connect(socket, &QTcpSocket::readyRead, [&, socket]() { qDebug() << "Server : " << socket->readAll(); }); });
|
客户端
客户端同理,使用前也要在cmake
工程文件里边添加network
模块
1 2 3
| find_package(Qt5 COMPONENTS core network REQUIRED)
target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Network)
|
客户端使用QTcpSocket
进行TCP通信
调用connectToHost
接口建立服务器通信连接
1 2
| QTcpSocket socket; socket.connectToHost(QHostAddress("127.0.0.1"), 9090);
|
需要处理几个跟连接相关的信号:connected、disconnected、readyRead
1 2 3 4 5 6 7 8 9 10 11 12 13
| QObject::connect(&socket, &QTcpSocket::connected, [&]() { timer->start(1000); qDebug() << "Client connected server"; });
QObject::connect(&socket, &QTcpSocket::disconnected, [&]() { qDebug() << "Client disconnected server"; });
QObject::connect(&socket, &QTcpSocket::readyRead, [&]() { qDebug() << "Client : " << socket.readAll(); });
|
基类QIODevice
的读写接口
1 2 3 4 5 6 7 8 9 10
| qint64 read(char *data, qint64 maxlen); QByteArray read(qint64 maxlen); QByteArray readAll(); qint64 readLine(char *data, qint64 maxlen); QByteArray readLine(qint64 maxlen = 0);
qint64 write(const char *data, qint64 len); qint64 write(const char *data); inline qint64 write(const QByteArray &data) { return write(data.constData(), data.size()); }
|
结果
- 以上的服务器和客户端在互相给对方发hello world数据
- QTcpServer那里巧妙抽象了QTcpSocket的操作方式,客户端和服务器都是对QTcpSocket读写