有一个例子WebSockets的Qt



是否有Qt的WebSockets示例?

你也可以看看QtWebSockets。QtWebSockets可用于客户端和服务器应用程序,并通过了Autobahn测试套件。

QtWebKit内部的QWebView支持使用Web Sockets(来自HTML5标准)。我已经用过很多次了,没有任何问题。

我创建了一个示例。下面是代码:

inspection_server.hpp:

#ifndef __INSPECTION_SERVER_HPP__
#define __INSPECTION_SERVER_HPP__
#include <QWebSocketServer>
#include <QWebSocket>
#include <QObject>
#include <iostream>
#include <memory>
class InspectionServer;
typedef std::shared_ptr<QWebSocketServer> QWebSocketServerPtr;
typedef std::shared_ptr<QWebSocket> QWebSocketPtr;
typedef std::shared_ptr<InspectionServer> InspectionServerPtr;
class InspectionServer: public QObject
{
    Q_OBJECT
    QWebSocketServerPtr websocketServer;
    QList<QWebSocketPtr> clients;
public:
    InspectionServer(uint16_t port);
signals:
    void closed();
private slots:
    void onNewConnection();
    void processTextMessage(const QString& message);
    void socketDisconnected();
};
#endif

inspection_server.cpp:

#include "inspection_server.hpp"
#include <QDebug>
InspectionServer::InspectionServer(uint16_t port)
    : websocketServer(new QWebSocketServer(QStringLiteral("Inspection server"), QWebSocketServer::NonSecureMode))
{
    if(this->websocketServer->listen(QHostAddress::Any, port))
    {
        QObject::connect(websocketServer.get(), SIGNAL(newConnection()), this, SLOT(onNewConnection()));
    }
    else
    {
        throw std::runtime_error("InspectionServer: failed to listen");
    }
}
void InspectionServer::onNewConnection()
{
    qInfo() << "InspectionServer::onNewConnection";
    QWebSocketPtr socket(this->websocketServer->nextPendingConnection());
    QObject::connect(socket.get(), SIGNAL(textMessageReceived(const QString&)), this, SLOT(processTextMessage(const QString&)));
    QObject::connect(socket.get(), SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
    this->clients.append(socket);
}
void InspectionServer::processTextMessage(const QString& message)
{
    qInfo() << "InspectionServer::processTextMessage: " << message;
}
void InspectionServer::socketDisconnected()
{
    qInfo() << "InspectionServer::socketDisconnected";
}

main.cpp:

#include "inspection_server.hpp"
#include <QCoreApplication>
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
    InspectionServer server(1234);
    return app.exec();
}
下面是在浏览器中测试的方法:
<html>
<body>
<button onClick="initWebSocket();">Connect</button>
<br>
<input type="text" id="messageInput">
<button onClick="sendMessage();">Send message</button>
</body>
</html>
<script type="text/javascript">
var websocket = null;
function initWebSocket()
{
    websocket = new WebSocket("ws://localhost:1234");
}
function sendMessage()
{
    websocket.send(document.getElementById("messageInput").value);
}
</script>

这是一个很好的参考链接:http://code.qt.io/cgit/qt/qtwebsockets.git/tree/examples/websockets/echoserver

最新更新