#include "widget.h" #include "ui_widget.h" #include Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); //创建对象 tcpServer = new QTcpServer(this); tcpSocket = new QTcpSocket(this); //2.有新连接时创建tcpSocket connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot())); } Widget::~Widget() { delete ui; } //打开服务器 void Widget::on_btnOpenServer_clicked() { //1.打开监听,所有地址,端口由输入框设定 if(tcpServer->listen(QHostAddress::Any,ui->tcpPort->text().toUInt())){ QMessageBox::information(this,"提示","正在监听"); }else{ QMessageBox::critical(this,"提示","失败"); } } //有新连接时创建tcpsocket void Widget::newConnection_Slot(){ if(tcpServer->hasPendingConnections()){ ui->messageRCV->appendPlainText("a client has connected!"); } //2.调用`nextPendingConnection()`来接受待处理的连接。返回一个连接的`QTcpSocket()` tcpSocket = tcpServer->nextPendingConnection(); //3.有数据时,读取tcpSocket数据 connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_SLOT())); } //3.有数据时,读取tcpSocket数据 void Widget::readyRead_SLOT(){ QString buff; buff = tcpSocket->readAll(); ui->messageRCV->appendPlainText(buff); } //4.关闭服务器 void Widget::on_btnCloseServer_clicked() { tcpServer->disconnect(); tcpServer->close(); if(tcpServer->isListening()){ QMessageBox::information(this,"提示","监听中。。"); }else{ QMessageBox::information(this,"提示","停止监听"); } } //5.发送数据 void Widget::on_btnSendMessage_clicked() { //toLocal8Bit()转化为字符数组,data()转化为字符指针 tcpSocket->write(ui->editMessageSend->text().toLocal8Bit().data()); } void Widget::on_btnCloseNow_clicked() { tcpSocket->close(); QMessageBox::information(this,"提示","已断开当前连接,继续监听中。。"); }