赞
踩
websocket 是基于 TCP socket 之上的应用层, 解决 HTML 轮询连接的问题,实现客户端与服务端长连接, 实现消息互相发送,全双工。
#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
/**************************************************************************** ** ** 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); // 对连接进来的每一个进行信号槽连接绑定 connect(pSocket, &QWebSocket::textMessageReceived, this, &ChatServer::processMessage); connect(pSocket, &QWebSocket::disconnected, this, &ChatServer::socketDisconnected); // 使用 list 进行管理,方便断开 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();
}
#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
#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); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。