是否有适用于Qt的WebSockets示例?
答案 0 :(得分:3)
您还可以查看QtWebSockets。 QtWebSockets可用于客户端和服务器应用程序,并通过Autobahn测试套件。
答案 1 :(得分:1)
QtWebKit内部的QWebView支持使用Web套接字(来自HTML5标准)。我已多次使用它们而没有任何问题。
答案 2 :(得分:0)
我创建了一个例子。这是代码:
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();
}
以下是在Web浏览器中测试的方法:
<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