Qt TCP/IP网络通信

TCP服务器部分:

cpp 复制代码
创建TCP服务器:
#include    <QTcpServer>
QTcpServer *tcpServer; //TCP服务器
tcpServer=new QTcpServer(this);

TCP服务器来连接的信号与槽:
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));

创建TCP套接字:
QTcpSocket *tcpSocket;//TCP通讯的Socket
在槽函数中:
void MainWindow::onNewConnection()
{
//    ui->plainTextEdit->appendPlainText("有新连接");
    tcpSocket = tcpServer->nextPendingConnection(); //创建socket

    connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(onClientConnected()));
    onClientConnected();//

    connect(tcpSocket, SIGNAL(disconnected()),
            this, SLOT(onClientDisconnected()));

    connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
    onSocketStateChange(tcpSocket->state());

    connect(tcpSocket,SIGNAL(readyRead()),
            this,SLOT(onSocketReadyRead()));
}

相关槽函数:
void MainWindow::onClientConnected()
{//客户端接入时
    ui->plainTextEdit->appendPlainText("**client socket connected");
    ui->plainTextEdit->appendPlainText("**peer address:"+
                                   tcpSocket->peerAddress().toString());
    ui->plainTextEdit->appendPlainText("**peer port:"+
                                   QString::number(tcpSocket->peerPort()));
}

void MainWindow::onClientDisconnected()
{//客户端断开连接时
    ui->plainTextEdit->appendPlainText("**client socket disconnected");
    tcpSocket->deleteLater();
    //    deleteLater();//QObject::deleteLater();
}

void MainWindow::onSocketStateChange(QAbstractSocket::SocketState socketState)
{//socket状态变化时
    switch(socketState)
    {
    case QAbstractSocket::UnconnectedState:
        LabSocketState->setText("scoket状态:UnconnectedState");
        break;
    case QAbstractSocket::HostLookupState:
        LabSocketState->setText("scoket状态:HostLookupState");
        break;
    case QAbstractSocket::ConnectingState:
        LabSocketState->setText("scoket状态:ConnectingState");
        break;

    case QAbstractSocket::ConnectedState:
        LabSocketState->setText("scoket状态:ConnectedState");
        break;

    case QAbstractSocket::BoundState:
        LabSocketState->setText("scoket状态:BoundState");
        break;

    case QAbstractSocket::ClosingState:
        LabSocketState->setText("scoket状态:ClosingState");
        break;

    case QAbstractSocket::ListeningState:
        LabSocketState->setText("scoket状态:ListeningState");
    }
}

void MainWindow::onSocketReadyRead()
{//读取缓冲区行文本
//    QStringList   lines;
    while(tcpSocket->canReadLine())
        ui->plainTextEdit->appendPlainText("[in] "+tcpSocket->readLine());
//        lines.append(clientConnection->readLine());
}

服务器开始监听:
tcpServer->listen(addr,port);//
停止监听:
if (tcpServer->isListening()) //tcpServer正在监听
    {
        tcpServer->close();//停止监听
}

发送数据:
void MainWindow::on_btnSend_clicked()
{//发送一行字符串,以换行符结束
    QString  msg=ui->editMsg->text();
    ui->plainTextEdit->appendPlainText("[out] "+msg);
    ui->editMsg->clear();
    ui->editMsg->setFocus();

    QByteArray  str=msg.toUtf8();
    str.append('\n');//添加一个换行符
    tcpSocket->write(str);
}

TCP客户端部分:

cpp 复制代码
#include    <QTcpSocket>
创建TCP套接字:
QTcpSocket  *tcpClient;  
tcpClient=new QTcpSocket(this); //创建socket变量
连接相关信号与槽:
connect(tcpClient,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(tcpClient,SIGNAL(disconnected()),this,SLOT(onDisconnected()));

    connect(tcpClient,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
    connect(tcpClient,SIGNAL(readyRead()),
            this,SLOT(onSocketReadyRead()));

void MainWindow::onSocketReadyRead()
{//readyRead()信号槽函数
    while(tcpClient->canReadLine())
        ui->plainTextEdit->appendPlainText("[in] "+tcpClient->readLine());
}
连接到服务器:
tcpClient->connectToHost(addr,port);
断开连接:
if (tcpClient->state()==QAbstractSocket::ConnectedState)
        tcpClient->disconnectFromHost();
发送数据:
void MainWindow::on_btnSend_clicked()
{//发送数据
    QString  msg=ui->editMsg->text();
    ui->plainTextEdit->appendPlainText("[out] "+msg);
    ui->editMsg->clear();
    ui->editMsg->setFocus();

    QByteArray  str=msg.toUtf8();
    str.append('\n');
    tcpClient->write(str);
}
相关推荐
n***s9091 小时前
IP地址、子网掩码(NETMASK)和网关(Gateway)
tcp/ip·gateway·智能路由器
e***74951 小时前
Modbus报文详解
服务器·开发语言·php
lly2024061 小时前
ASP 发送电子邮件详解
开发语言
小徐敲java1 小时前
python使用s7协议与plc进行数据通讯(HslCommunication模拟)
开发语言·python
likuolei1 小时前
XSL-FO 软件
java·开发语言·前端·数据库
6***37941 小时前
PHP在电商中的BigCommerce
开发语言·php
Dev7z1 小时前
基于Matlab的多制式条形码识别与图形界面(GUI)系统设计与实现
开发语言·matlab
合作小小程序员小小店1 小时前
桌面开发,在线%信息管理%系统,基于vs2022,c#,winform,sql server数据。
开发语言·数据库·sql·microsoft·c#
FL16238631291 小时前
ONNX RuntimeC++ 静态库下载安装和使用教程
开发语言·c++
星释1 小时前
Rust 练习册 95:React与响应式编程
开发语言·react.js·rust