Node.js event-driven server-side web socket, perfectly supporting QT QWebSocket as client.
npm install --save node-qwebsocket
const hostname = '127.0.0.1';
const port = 4000;
const http = require('http');
const server = http.createServer(function (req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, function () {
console.log('Server running at http://%s:%s/', hostname, port);
});
const WebSocketServer = require('node-qwebsocket');
const socketServer = new WebSocketServer(server);
socketServer.on('connection', function (socket) {
console.log('socket connected!');
socket.on('close', function () {
console.log('socket closed...');
});
});
QWebSocket webSocket;
webSocket.open(QUrl("ws://127.0.0.1:4000"));
const socketServer = new WebSocketServer(server);
socketServer.on('connection', function (socket) {
socket.on('setup', function (data) {
console.log('setup event: %s', JSON.stringify(data, null, 2));
socket.emit('response', { message: 'Hello Client!' });
});
});
connect(&webSocket, &QWebSocket::connected, this, &SocketManager::onConnected, Qt::UniqueConnection);
connect(&webSocket, &QWebSocket::textMessageReceived, this, &SocketManager::onTextMessageReceived, Qt::UniqueConnection);
in onConnected()
SLOT:
QJsonObject payload;
payload["content"] = "it's setup";
QJsonObject message;
message["event"] = event;
message["payload"] = payload;
QJsonDocument doc(message);
QByteArray bytes = doc.toJson();
webSocket.sendTextMessage(QString(bytes));
in onTextMessageReceived(message)
SLOT:
qDebug() << message;
Sending/receiving in QT is structured as:
{
event: <eventName>,
payload: {
<...payloadContent>
}
}
socket.on('connection', function (socket) {
socket.on('message', function (data) {
console.log('received raw message: %s', JSON.stringify(data, null, 2));
});
});
MIT