作业要求:
1.思维导图
2.整理代码:TCP服务器
作业1:思维导图
作业2:整理代码
运行代码:
widget.h
cpp
#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_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
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.创建好套接字后,首先绑定port
quint16 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);
}
}
}
}