Qt5 TCP通信

服务器端

 //服务器端需要两种套接字
    QTcpServer *tcpServer;//监听套接字
    QTcpSocket *tcpSocket;//通信套接字

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("服务器端");
    tcpServer = new QTcpServer(this); //指定父对象
    tcpServer->listen(QHostAddress::Any, 8888); //监听套接字 地址+端口
    connect(tcpServer, &QTcpServer::newConnection,//等待客户端的连接请求
            [=]()
            {
                tcpSocket = tcpServer->nextPendingConnection();//取出通信套接字
                QHostAddress hostip = tcpSocket->peerAddress();
                quint16 hostport = tcpSocket->peerPort();
                QString str=QString("[%1:%2] connect").arg(hostip.toString()).arg(hostport);
                ui->textEditread->setText(str);//显示连接成功信息
                //显示客服端发送的信息
                connect(tcpSocket,&QTcpSocket::readyRead,//只要通信套接字中有内容就调用readyread函数
                        [=]()
                        {
                            QByteArray array = tcpSocket->readAll();
                            ui->textEditread->append(array.data());
                        }
                );
            }
    );
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_SendButton_clicked()
{
    QString str= ui->textEditwrite->toPlainText();
    //将服务器端的信息发送出去
    tcpSocket->write(str.toUtf8().data());

}

void Widget::on_CloseButton_clicked()
{
    //tcpServer->disconnect();
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

客户端

//客户端只需要通信套接字
    QTcpSocket *tcpSocket;
Client::Client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    setWindowTitle("Client");
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket,&QTcpSocket::connected,//判断连接请求是否成功
            [=]()
            {
               ui->textEditRead->setText("与服务器链接成功");
            }
    );
    //接收服务器发送过来的数据
    connect(tcpSocket,&QTcpSocket::readyRead,
            [=]()
            {
               QByteArray array = tcpSocket->readAll();
               ui->textEditRead->append(array);
            }
    );
}

Client::~Client()
{
    delete ui;
}

void Client::on_ConnectButton_clicked()
{
    //客户端首先发送连接请求
    QString ip=ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toInt();
    tcpSocket->connectToHost(QHostAddress(ip),port);//向服务器发送链接请求
}

void Client::on_SendButton_clicked()//向服务器端发送消息
{
    QString str = ui->textEditWrite->toPlainText();
    tcpSocket->write(str.toUtf8().data());//字符串只能先转utf8才能再转char*
}

void Client::on_CloseButton_clicked()
{
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值