node-qwebsocket
v1.0.1
Published
node.js event-driven websocket as server, supporting QT QWebSocket as client
Downloads
9
Readme
node-qwebsocket
Node.js event-driven server-side web socket, perfectly supporting QT QWebSocket as client.
Installing
npm install --save node-qwebsocket
Usage
Basic example
sever side
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...');
});
});
client side (QT)
QWebSocket webSocket;
webSocket.open(QUrl("ws://127.0.0.1:4000"));
Receive and emit customized event
server side
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!' });
});
});
client side
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>
}
}
Receiving raw data
socket.on('connection', function (socket) {
socket.on('message', function (data) {
console.log('received raw message: %s', JSON.stringify(data, null, 2));
});
});
License
MIT