QT开启websocket server(QWebSocketServer) 网页做为客户端
https://stackoverflow.com/questions/5673827/is-there-an-example-websockets-for-qt
QT项目中
.pro文件:
QT += core gui #获取串口列表倒包 QT += serialport #创建websocket倒包 QT += websockets
inspection_server.h :
#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.h" #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 "mainwindow.h" #include <QApplication> //导入串口包 #include <QCoreApplication> #include <QList> #include <stdio.h> #include <QDebug> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> //创建websocket #include <QWebSocketServer> #include "inspection_server.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); // MainWindow w; // w.show(); qDebug()<< "main.cpp执行了"; InspectionServer server(1234); return a.exec(); }
打开一个网页index.html (必须使用node等脚本开启html服务 , http://localhost:5050/)
start.js :
var http = require('http');//创建服务器的 var fs = require('fs'); //引入进来的是模块,模块中有方法,下一步就是使用方法 //Node.js一个最主要的特点:执行的基本都是函数 //创建服务 var myServer = http.createServer(function(req,res){ //req->请求变量:客户端请求服务器的 //res->响应变量:服务器要给客户端写回的变量 //前端页面应该给客户端显示,即写回去 //这之前应该先把文件内容读出来 var html = fs.readFileSync('./index.html') res.write(html); //结束写的操作 res.end(); }) //服务端等着客户端请求需要做一个监听。通过创建的服务。 //监听 myServer.listen('5050',function(err){ if(err){ console.log(err); throw err; } console.log("服务器已开启。端口号为:5050"); }) //浏览器请求服务器。知道当前计算机的ip地址。例如,127.0.0.1:3000
index.html :
<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; var start = function () { websocket = new WebSocket("ws://localhost:1234"); } websocket.onopen = function () { console.log('链接开始了') } ws.onmessage = function (evt) { var received_msg = evt.data; console.log("数据已接收...", received_msg); }; ws.onclose = function () { // 关闭 websocket alert("连接已关闭..."); }; //直接开启websocket start(); function sendMessage() { websocket.send(document.getElementById("messageInput").value); } </script>
最后一步,执行脚本命令开启服务:
node start.js
效果:
在浏览器中打开http://localhost:5050/这个地址的网页,如下图。
在QT的IDE控制台中会打印出LOG: