You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.6 KiB

2 years ago
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//1.socket对象
tcpSocket = new QTcpSocket(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btnConnect_clicked()
{
//2.打开连接
tcpSocket->connectToHost(ui->editIpInput->text(),ui->editPortInput->text().toUInt());
if(tcpSocket->waitForConnected(1000)){
QMessageBox::information(this,"提示","连接成功");
}else{
QMessageBox::critical(this,"提示","连接失败");
}
//3.连接成功时连接函数
//3.`connected()`这个信号在调用connectToHost()并成功建立连接之后发出。
connect(tcpSocket,SIGNAL(connected()),this,SLOT(connected_Slot()));
}
//3.连接成功槽函数
void Widget::connected_Slot(){
//4.新数据时,连接函数
//`readyRead()`有新数据到来时触发
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
//4.新数据时槽函数
//发送数据到接收框
void Widget::readyRead_Slot(){
QString buff;
buff = tcpSocket->readAll();
ui->pteMessageRCV->appendPlainText(buff);
}
//5.发送数据槽函数
void Widget::on_btnSend_clicked()
{
//toLocal8Bit()转化为字符数组,data()转化为字符指针
tcpSocket->write(ui->editMessageSend->text().toLocal8Bit().data());
}
//6.关闭连接槽函数
void Widget::on_btnClose_clicked()
{
tcpSocket->close();
//tcpSocket->disconnectFromHost();
QMessageBox::information(this,"提示","断开连接");
}