Qt自带的有网络编程模块,需要再pro文件加上 websockets
# pro 文件 QT += core gui websockets
.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QWebSocketServer> #include <QWebSocket> #include <QDebug> QT_BEGIN_NAMESPACE namespace Ui { class Widget; } QT_END_NAMESPACE class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = nullptr); ~Widget(); signals: void signale_sendToClient(const QByteArray &data); public slots: void sendToClient(const QByteArray &data); void onopen(); void onclose(); void onMessage(const QString &message); private: Ui::Widget *ui; QWebSocketServer *ws = nullptr; QList<QWebSocket *> m_clients; }; #endif // WIDGET_H
.cpp
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); ws = new QWebSocketServer("server", QWebSocketServer::NonSecureMode, this); ws->listen(QHostAddress::Any, 36668); connect(ws, &QWebSocketServer::newConnection, this, &Widget::onopen); showMinimized(); } Widget::~Widget() { if(ws) { ws->close(); ws->deleteLater(); } delete ui; } void Widget::sendToClient(const QByteArray &data) { for (QWebSocket *p_client: qAsConst(m_clients)) { p_client->sendTextMessage(QString("send data to client")); } } void Widget::onopen() { auto p_socket = ws->nextPendingConnection(); qDebug() << "websocket onopen..."; connect(p_socket, &QWebSocket::textMessageReceived, this, &Widget::onMessage); connect(p_socket, &QWebSocket::disconnected, this, &Widget::onclose); m_clients << p_socket; } void Widget::onclose() { QWebSocket *p_client = qobject_cast<QWebSocket*>(sender()); qDebug() << "websocket onclose..."; if(p_client) { m_clients.removeAll(p_client); p_client->deleteLater(); } } void Widget::onMessage(const QString &message) { // 打印 接受到的消息 qDebug() << "websocket message:" << message; }
标签:Widget,ui,websocket,Qt,void,开发,ws,const,include From: https://www.cnblogs.com/shiyixirui/p/18181476