Qt Tcp通信和windows的类似,分服务端和客户端,模型如下
windows的Tcp通信可以看这篇文章:【请点击查看】
Qt的Tcp主要涉及到两类,QTcpServer和QTcpSocket, 对于服务端需要两个socket, 一个用于监听客户端连接,也就是QTcpServer,另一个用于和客户端通信, 也就是QTcpSocket; 客户端只需要一个socket. 写一个简单的demo, 服务端和客户端各用一个窗口表示:
代码大同小异,服务端
server.cpp
#include "server.h" #include "ui_server.h" Server::Server(QWidget *parent) : QWidget(parent), ui(new Ui::Server) { ui->setupUi(this); this->setFixedSize(500,700); ui->sIP->setText("127.0.0.1"); ui->sPort->setText("8765"); // 创建监听套接字 server = new QTcpServer(this); // 监听 server->listen(QHostAddress(ui->sIP->text()), ui->sPort->text().toInt()); // 新的链接 connect(server, &QTcpServer::newConnection, this, [=]() { conn = server->nextPendingConnection(); // 返回客户端的套接字对象地址 ui->record->append("had new client connect....."); // 接收客户端消息 connect(conn, &QTcpSocket::readyRead, this, [=]() { QByteArray array = conn->readAll(); ui->record->append(array); }); }); } Server::~Server() { delete ui; } void Server::on_sendBtn_clicked() { // 发送数据 conn->write(ui->msg->toPlainText().toUtf8()); ui->record->append("Server Say: " + ui->msg->toPlainText()); // 清楚发送消息框的内容 ui->msg->clear(); }
客户端 client.cpp
#include "client.h" #include "ui_client.h" #includeClient::Client(QWidget *parent) : QWidget(parent), ui(new Ui::Client) { ui->setupUi(this); this->setFixedSize(500,700); ui->sIP->setText("127.0.0.1"); ui->sPort->setText("8765"); //创建通信套接字 client = new QTcpSocket(this); // 连接接服务器 client->connectToHost(QHostAddress(ui->sIP->text()), ui->sPort->text().toInt()); // 接收数据 connect(client, &QTcpSocket::readyRead, this, [=]() { QByteArray array = client->readAll(); ui->record->append(array); }); } Client::~Client() { delete ui; } void Client::on_sendBtn_clicked() { client->write(ui->msg->toPlainText().toUtf8()); ui->record->append("Client Say: " + ui->msg->toPlainText()); ui->msg->clear(); }
main函数中把两个窗口都显示出来,
#include "server.h" #include#include "client.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Server w; w.setWindowTitle("server"); w.show(); Client c; c.setWindowTitle("client"); c.show(); return a.exec(); }
demo比较简单,按照开篇的图进行编写代码即可。