widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QList>
#include <QMessageBox>
#include <QDebug>
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_btn_clicked();
void newConnection_slot();
void readyRead_slot();
private:
Ui::Widget *ui;
QTcpServer *server;
QList<QTcpSocket *> clientList;
};
#endif // WIDGET_H
main.cpp文章来源:https://www.toymoban.com/news/detail-729131.html
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.cpp文章来源地址https://www.toymoban.com/news/detail-729131.html
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
server = new QTcpServer(this);
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btn_clicked()
{
quint16 port = ui->lineEdit->text().toUInt();
if(!ui->lineEdit->text().isEmpty() && !server->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"失败","监听失败");
return ;
}
else
{
QMessageBox::information(this,"成功","监听成功");
}
}
void Widget::newConnection_slot()
{
QTcpSocket *s = server->nextPendingConnection();
clientList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
void Widget::readyRead_slot()
{
for(int i = 0; i < clientList.size(); i++)
{
if(clientList[i]->state() == 0)
{
clientList.removeAt(i);
}
}
for(int i = 0; i < clientList.size(); i++)
{
if(clientList[i]->bytesAvailable() != 0)
{
QByteArray msg = clientList[i]->readAll();
ui->listWidget->addItem(QString::fromLocal8Bit(msg));
for(int j = 0; j < clientList.size(); j++)
{
clientList[j]->write(msg);
}
}
}
}
到了这里,关于国庆第五天的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!