Qt网络通信——TCP和UDP

一、TCP通信

        TCP通信必须先建立 TCP 连接,通信端分为客户端和服务器端。

        Qt 为服务器端提供了 QTcpServer 类用于实现端口监听,QTcpSocket 类则用于服务器和客户端之间建立连接。大致流程如下图所示:

Qt网络通信——TCP和UDP_第1张图片

1. 服务器端建立

1.1 监听——listen()

        服务器端程序首先需要用函数 listen() 开始服务器监听,可以设置监听的IP地址和端口,一般一个服务器端程序只监听某个端口的网络连接。函数原型定义如下:

bool QTcpServer::listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0)

        函数返回 true 时,表示监听成功。此时服务器会持续监听来自客户端的连接请求。举例:

if (!tcpServer->listen(QHostAddress::LocalHost, 8080)) {    
    QMessageBox::information(this, "Error", tcpServer->errorString());
    return;
}

        那么在什么情况下会监听失败呢?

  1. 端口号太低导致冲突或者没有权限;
  2. 监听除了127.0.0.1和0.0.0.0以外的端口,可能需要管理员权限。
 1.2 接受连接——nextPendingConnection()

        当有新的客户端接入时,QTcpServer的内部有一个受保护函数 incomingConnection(),它会创建一个与客户端连接的QTcpSocket对象,然后发射 newConnection() 信号。

        此时,可以建立自定义槽函数对该信号进行处理,使用 nextPendingConnection() 建立socket连接。

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    ...

    tcpServer = new QTcpServer(this);
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(do_newConnection()));
}

void MainWindow::do_newConnection()
{
    tcpSocket = tcpServer->nextPendingConnection(); //创建socket接收客户端连接   

    ...
}

2. 客户端建立

        客户端的 QTcpSocket 对象首先通过 connectToHost() 尝试连接到服务器

你可能感兴趣的:(qt,tcp/ip,udp)