在qt下,实现基于tcp通信

server:

#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
    : QWidget(parent) , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //实例化通信套接字和监听套接字
    tcpServer = new QTcpServer(this);
    tcpSocket = new QTcpSocket(this);
    //有新连接的,就获得其socket
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_slot()));
}
//获取socket
void Widget::newConnection_slot()
{
    //接收来自客户端的通信套接字对象
    tcpSocket = tcpServer->nextPendingConnection();
    //显示已经连接
    ui->recvEdits->appendPlainText("有新的连接");
    //获得socket以后,准备开始读
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyReads_Slot()));
}
void Widget::readyReads_Slot()
{
    QString buf;
    buf = tcpSocket->readAll();
    ui->recvEdits->appendPlainText(buf);
}
//建立连接按钮
void Widget::on_openBts_clicked()
{
    //监听来自客户端的连接
    tcpServer->listen(QHostAddress::Any,ui->portEdits->text().toUInt());
}
void Widget::on_closeBts_clicked()
{
    tcpServer->close();
}
void Widget::on_sendBts_clicked()
{
    tcpSocket->write(ui->sendEdits->text().toLocal8Bit().data());
    //清空发送框里面的内容
    ui->sendEdits->clear();
}

client:

#include "client.h"
#include "ui_client.h"
client::client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::client)
{
    ui->setupUi(this);
    //通信套接字
    tcpclient = new QTcpSocket(this);
}
void client::on_openBt_clicked()
{
    //连接服务器
     tcpclient->connectToHost(ui->ipEdit->text(),ui->portEdit->text().toUInt());
     connect(tcpclient,SIGNAL(connected()),this,SLOT(connected_slot()));
}
void client::connected_slot()
{
    connect(tcpclient,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));
}
//显示从服务器发来的内容
void client::readyRead_slot()
{
    ui->recvEdit->appendPlainText(tcpclient->readAll());
}
void client::on_closeBt_clicked()
{
    tcpclient->close();
}
//发送数据给服务器
void client::on_sendBt_clicked()
{
    tcpclient->write(ui->sendEdit->text().toLocal8Bit().data());
    ui->sendEdit->clear();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

One Piece&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值