国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

qt websocket 通訊實(shí)現(xiàn)消息發(fā)送接收

這篇具有很好參考價(jià)值的文章主要介紹了qt websocket 通訊實(shí)現(xiàn)消息發(fā)送接收。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

websocket 是基于 TCP socket 之上的應(yīng)用層, 解決 HTML 輪詢連接的問題,實(shí)現(xiàn)客戶端與服務(wù)端長連接, 實(shí)現(xiàn)消息互相發(fā)送,全雙工。

  1. 服務(wù)端, 使用 QT 教程demo
    chatserver.h

#ifndef CHATSERVER_H
#define CHATSERVER_H

#include <QtCore/QObject>
#include <QtCore/QList>

QT_FORWARD_DECLARE_CLASS(QWebSocketServer)
QT_FORWARD_DECLARE_CLASS(QWebSocket)
QT_FORWARD_DECLARE_CLASS(QString)

class ChatServer : public QObject
{
    Q_OBJECT
public:
    explicit ChatServer(quint16 port, QObject *parent = nullptr);
    ~ChatServer() override;

private slots:
    void onNewConnection();
    void processMessage(const QString &message);
    void socketDisconnected();

private:
    QWebSocketServer *m_pWebSocketServer;
    QList<QWebSocket *> m_clients;
};

#endif //CHATSERVER_H

  1. chatserver.cpp
/****************************************************************************
**
** Copyright (C) 2016 Kurt Pattyn <pattyn.kurt@gmail.com>.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWebSockets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "chatserver.h"

#include <QtWebSockets>
#include <QtCore>

#include <cstdio>
using namespace std;

QT_USE_NAMESPACE

static QString getIdentifier(QWebSocket *peer)
{
    return QStringLiteral("%1:%2").arg(peer->peerAddress().toString(),
                                       QString::number(peer->peerPort()));
}

//! [constructor]
ChatServer::ChatServer(quint16 port, QObject *parent) :
    QObject(parent),
    m_pWebSocketServer(new QWebSocketServer(QStringLiteral("Chat Server"),
                                            QWebSocketServer::NonSecureMode,
                                            this))
{
    if (m_pWebSocketServer->listen(QHostAddress::Any, port))
    {
        QTextStream(stdout) << "Chat Server listening on port " << port << '\n';
        connect(m_pWebSocketServer, &QWebSocketServer::newConnection,
                this, &ChatServer::onNewConnection);
    }
}

ChatServer::~ChatServer()
{
    m_pWebSocketServer->close();
}
//! [constructor]

//! [onNewConnection]
void ChatServer::onNewConnection()
{
    auto pSocket = m_pWebSocketServer->nextPendingConnection();
    QTextStream(stdout) << getIdentifier(pSocket) << " connected!\n";
    pSocket->setParent(this);

    // 對(duì)連接進(jìn)來的每一個(gè)進(jìn)行信號(hào)槽連接綁定
    connect(pSocket, &QWebSocket::textMessageReceived,
            this, &ChatServer::processMessage);
    connect(pSocket, &QWebSocket::disconnected,
            this, &ChatServer::socketDisconnected);

    // 使用 list 進(jìn)行管理,方便斷開
    m_clients << pSocket;
}
//! [onNewConnection]

//! [processMessage]
void ChatServer::processMessage(const QString &message)
{
    QWebSocket *pSender = qobject_cast<QWebSocket *>(sender());
    for (QWebSocket *pClient : qAsConst(m_clients)) {
        if (pClient == pSender) //don't echo message back to sender
        {
            pClient->sendTextMessage(message + " @ host echo ");
            qDebug() << "peer address = " << pClient->peerAddress();
        }
    }
    QTextStream(stdout) << "received msg: " << message << std::endl;
}
//! [processMessage]

//! [socketDisconnected]
void ChatServer::socketDisconnected()
{
    QWebSocket *pClient = qobject_cast<QWebSocket *>(sender());
    QTextStream(stdout) << getIdentifier(pClient) << " disconnected!\n";
    if (pClient)
    {
        m_clients.removeAll(pClient);
        pClient->deleteLater();
    }
}
//! [socketDisconnected]

main.cpp

#include <QtCore/QCoreApplication>

#include "chatserver.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    ChatServer server(1234);

    return a.exec();
}
  1. 客戶端
    clientwidget.h
#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H

#include <QWidget>
#include "WebsocketClient.h"

QT_FORWARD_DECLARE_CLASS(QWebSocketClient)
QT_FORWARD_DECLARE_CLASS(QWebSocket)

namespace Ui {
class ClientWidget;
}

class ClientWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ClientWidget(QWidget *parent = 0);
    ~ClientWidget();

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

    void slot_recvMsg(QString msg);

private:
    Ui::ClientWidget *ui;

    WebsocketClient m_client;
};

#endif // CLIENTWIDGET_H

clientwidget.cpp

#include "ClientWidget.h"
#include "ui_ClientWidgetwidget.h"

ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);


}

ClientWidget::~ClientWidget()
{
    delete ui;
}

void ClientWidget::on_pushButton_clicked()
{
    m_client.connectToServer();

    connect(&m_client, &WebsocketClient::sig_newMsg, this, &ClientWidget::slot_recvMsg);
}

void ClientWidget::on_pushButton_2_clicked()
{
    m_client.sendMsg(ui->lineEditSendTxt->text());
}

void ClientWidget::slot_recvMsg(QString msg)
{
    ui->textBrowserRecv->append(msg);
}

websocketclient.h

#ifndef WEBSOCKETCLIENT_H
#define WEBSOCKETCLIENT_H

#include <QDebug>
#include <QWebSocket>
QT_FORWARD_DECLARE_CLASS(QWebSocketClient)
QT_FORWARD_DECLARE_CLASS(QWebSocket)

class WebsocketClient:public QObject
{
    Q_OBJECT
public:
    WebsocketClient();

    //connect to server
    void connectToServer();

    bool sendMsg(QString msg);

    void disConnect();

public slots:
    void slot_recvMsg(QString msg);

signals:
    void sig_newMsg(QString msg);

private:
    QWebSocket m_clientSocket;
};

#endif // WEBSOCKETCLIENT_H

websocketclient.cpp文章來源地址http://www.zghlxwxcb.cn/news/detail-613652.html

#include "WebsocketClient.h"

WebsocketClient::WebsocketClient()
{

}

void WebsocketClient::connectToServer()
{
    QString urlStr = "ws://127.0.0.1:1234";
    m_clientSocket.open(QUrl(urlStr));
    connect(&m_clientSocket, &QWebSocket::textMessageReceived, this, &WebsocketClient::slot_recvMsg);
}

bool WebsocketClient::sendMsg(QString msg)
{
    if (m_clientSocket.sendTextMessage(msg)) {
        return true;
    }
    else {
           return false;
    }
}

void WebsocketClient::disConnect()
{
    m_clientSocket.close();
}

void WebsocketClient::slot_recvMsg(QString msg)
{
    qDebug() << "client received from host: " << msg;
    emit sig_newMsg(msg);
}

到了這里,關(guān)于qt websocket 通訊實(shí)現(xiàn)消息發(fā)送接收的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Qt實(shí)現(xiàn)UDP發(fā)送與接收操作

    目錄 一、為什么要寫這篇文章,因?yàn)槲揖褪且肀脔鑿?,?dāng)然也是汲取了網(wǎng)上大咖們的經(jīng)驗(yàn),盡量簡(jiǎn)潔的進(jìn)行總結(jié) 二、關(guān)于接收數(shù)據(jù)需的條件,需要綁定本地IP地址和端口號(hào),可解釋為此時(shí)為服務(wù)器模式,遠(yuǎn)端為客戶端模式,實(shí)現(xiàn)的代碼非常簡(jiǎn)單幾行代碼可以搞定 三、數(shù)據(jù)

    2024年02月11日
    瀏覽(15)
  • 【QT實(shí)現(xiàn)TCP數(shù)據(jù)發(fā)送和接收】

    單客戶端服務(wù)器實(shí)現(xiàn)代碼: 在.pro文件添加 在頭文件中添加 在源文件中添加

    2024年02月11日
    瀏覽(21)
  • QT網(wǎng)絡(luò)編程之實(shí)現(xiàn)UDP廣播發(fā)送和接收

    一.UDP廣播介紹 UDP廣播地址固定IP地址為:XXX.XXX.XXX.255。 如果向全網(wǎng)段發(fā)送廣播消息,那么廣播地址為:255.255.255.255; 如果向單個(gè)網(wǎng)段發(fā)送廣播消息,例如你的IP是192.168.31.104,那么廣播地址為192.168.31.255。 廣播消息接收方需要綁定0.0.0.0地址并監(jiān)聽指定端口即可收到廣播的群

    2024年03月25日
    瀏覽(50)
  • QT三駕馬車(一)——實(shí)現(xiàn)上位機(jī)(串口數(shù)據(jù)發(fā)送和接收)

    QT三駕馬車(一)——實(shí)現(xiàn)上位機(jī)(串口數(shù)據(jù)發(fā)送和接收)

    以后同學(xué)們做項(xiàng)目一定會(huì)用到QT的三駕馬車,QT的三駕馬車即QT的串口編程,QT的網(wǎng)絡(luò)編程和QT的GPIO,今天我們通過一個(gè)項(xiàng)目來介紹第一部分,QT的串口編程。 之前看過很多相關(guān)的文章,但是按照順序來編譯總是會(huì)出錯(cuò),可是我自己還找不到原因,對(duì)于我這種新手小白來說極其

    2024年02月15日
    瀏覽(21)
  • Qt實(shí)現(xiàn)客戶端與服務(wù)器消息發(fā)送

    Qt實(shí)現(xiàn)客戶端與服務(wù)器消息發(fā)送

    里用Qt來簡(jiǎn)單設(shè)計(jì)實(shí)現(xiàn)一個(gè)場(chǎng)景,即: (1)兩端:服務(wù)器QtServer和客戶端QtClient (2)功能:服務(wù)端連接客戶端,兩者能夠互相發(fā)送消息,傳送文件,并且顯示文件傳送進(jìn)度。 環(huán)境:VS20013 + Qt5.11.2 + Qt設(shè)計(jì)師 先看效果: 客戶端與服務(wù)器的基本概念不說了,關(guān)于TCP通信的三次握

    2024年02月11日
    瀏覽(22)
  • RabbitMQ-同步和異步通訊、安裝和入門案例、SpringAMQP(5個(gè)消息發(fā)送接收Demo,jackson消息轉(zhuǎn)換器)

    RabbitMQ-同步和異步通訊、安裝和入門案例、SpringAMQP(5個(gè)消息發(fā)送接收Demo,jackson消息轉(zhuǎn)換器)

    微服務(wù)間通訊有同步和異步兩種方式: 同步通訊:就像打電話,需要實(shí)時(shí)響應(yīng)。 異步通訊:就像發(fā)郵件,不需要馬上回復(fù)。 兩種方式各有優(yōu)劣,打電話可以立即得到響應(yīng),但是你卻不能跟多個(gè)人同時(shí)通話。發(fā)送郵件可以同時(shí)與多個(gè)人收發(fā)郵件,但是往往響應(yīng)會(huì)有延遲。 1.

    2024年02月11日
    瀏覽(16)
  • Qt進(jìn)行UDP通訊,創(chuàng)建一個(gè)收線程這樣可以進(jìn)行接收數(shù)據(jù)

    Qt進(jìn)行UDP通訊,創(chuàng)建一個(gè)收線程這樣可以進(jìn)行接收數(shù)據(jù)

    在.pro中增加一句話 繪制界面 .h文件內(nèi)容: 構(gòu)造函數(shù)內(nèi)容 對(duì)于綁定按鈕的定義函數(shù): 接收信號(hào)的槽函數(shù)(UDP接收到數(shù)據(jù)顯示) quitThreaSlot函數(shù): 退出按鈕定義: 使用的receivethread.h就是將run函數(shù)重寫(循環(huán)發(fā)送定義的信號(hào)延遲即可),在定義一個(gè)信號(hào)即可。 以上即功能的所有

    2024年02月20日
    瀏覽(31)
  • Qt+C++串口調(diào)試接收發(fā)送數(shù)據(jù)曲線圖

    Qt+C++串口調(diào)試接收發(fā)送數(shù)據(jù)曲線圖

    程序示例精選 Qt+C++串口調(diào)試接收發(fā)送數(shù)據(jù)曲線圖 如需安裝運(yùn)行環(huán)境或遠(yuǎn)程調(diào)試,見文章底部個(gè)人 QQ 名片,由專業(yè)技術(shù)人員遠(yuǎn)程協(xié)助! 這篇博客針對(duì)Qt+C++串口調(diào)試接收發(fā)送數(shù)據(jù)曲線圖編寫代碼,代碼整潔,規(guī)則,易讀。 學(xué)習(xí)與應(yīng)用推薦首選。 一、所需工具軟件 二、使用步驟

    2024年02月11日
    瀏覽(95)
  • Kafka消息隊(duì)列實(shí)現(xiàn)消息的發(fā)送和接收

    Kafka消息隊(duì)列實(shí)現(xiàn)消息的發(fā)送和接收

    消息在Kafka消息隊(duì)列中發(fā)送和接收過程如下圖所示: 消息生產(chǎn)者Producer產(chǎn)生消息數(shù)據(jù),發(fā)送到Kafka消息隊(duì)列中,一臺(tái)Kafka節(jié)點(diǎn)只有一個(gè)Broker,消息會(huì)存儲(chǔ)在Kafka的Topic(主題中),不同類型的消息數(shù)據(jù)會(huì)存儲(chǔ)在不同的Topic中,可以利用Topic實(shí)現(xiàn)消息的分類,消息消費(fèi)者Consumer會(huì)訂閱

    2024年02月11日
    瀏覽(21)
  • Java 構(gòu)建websocket客戶端,構(gòu)建wss客戶端,使用wss連接,并發(fā)送數(shù)據(jù)到服務(wù)器端,接收服務(wù)器端消息

    Java 構(gòu)建websocket客戶端,構(gòu)建wss客戶端,使用wss連接,并發(fā)送數(shù)據(jù)到服務(wù)器端,接收服務(wù)器端消息 回調(diào)函數(shù)處理

    2024年02月13日
    瀏覽(33)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包