作业要求:
1.思维导图
2.整理代码:TCP服务器
作业1:思维导图
作业2:整理代码
运行代码:
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer>
#include <QList>
#include <QMessageBox>
#include <QTcpSocket>
#include <QByteArray>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private slots:void on_startBtn_clicked();void newConnection_slot();void readyRead_slot();private:Ui::Widget *ui;//套接字文件QTcpServer *server;QList<QTcpSocket *> socketlist;};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget),server(new QTcpServer(this))
{ui->setupUi(this);
}Widget::~Widget()
{delete ui;
}void Widget::on_startBtn_clicked()
{//1.创建好套接字后,首先绑定portquint16 port = ui->portEdit->text().toUInt();//2.开启监听if(server->listen(QHostAddress::Any,port)){//开启监听成功QMessageBox::information(this,"提示","开启监听成功",QMessageBox::Ok);}else{//开启监听失败QMessageBox::information(this,"提示","开启监听失败",QMessageBox::Ok);return;}//运行至此,开始连接newConnection()函数和槽connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);}void Widget::newConnection_slot()
{//进入该函数,说明接受到客户端的连接//1.创建用于通信的套接字文件QTcpSocket *s = server->nextPendingConnection();//2.放入套接字容器socketlist.push_back(s);//发送信号readyread,将套接字与对应槽函数连接,从而可以实现通信。connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}void Widget::readyRead_slot()
{//首先去除无效套接字文件。for(int i=0;i<socketlist.count();i++){if(socketlist.at(i)->state()==0){//说明无效,从列表中去除socketlist.removeAt(i);}}//接受信息for(int i=0;i<socketlist.count();i++){if(socketlist.at(i)->bytesAvailable()!=0){//说明接受到了信息QByteArray msg = socketlist.at(i)->readAll();ui->msgList->addItem(QString::fromLocal8Bit(msg));for(int j=0;j<socketlist.count();j++){socketlist.at(j)->write(msg);}}}
}