我正在尝试将 Node.js WebSockets 与sharedb
. 这是我到目前为止所拥有的
var http = require('http');
var express = require('express');
var ShareDB = require('sharedb');
var WebSocket = require('ws');
var WebSocketJSONStream = require('websocket-json-stream');
var ShareDBLogger = require('sharedb-logger');
var backend = new ShareDB();
createDoc(startServer);
// Create initial document then fire callback
function createDoc(callback) {
var connection = backend.connect();
const sharedbLogger = new ShareDBLogger(backend);
var doc = connection.get('examples', 'text');
doc.fetch(function(err) {
if (err) throw err;
if (doc.type === null) {
doc.create({content: 'Hello'}, 'text', callback);
return;
}
callback();
});
}
function startServer() {
// Create a web server to serve files and listen to WebSocket connections
var app = express();
var server = http.createServer(app);
// Connect any incoming WebSocket connection to ShareDB
var wss = new WebSocket.Server({server: server});
wss.on('connection', function(ws, req) {
var stream = new WebSocketJSONStream(ws);
backend.listen(stream);
ws.on('message', function (data) {
const json = JSON.parse(data);
if(json.type === 'request-id') ws.send('some-id');
})
});
server.listen(8080);
console.log('Listening on http://localhost:8080');
}
但是,由于我的客户端发送的 WebSocket 消息{type: 'request-id'}
不是sharedb
标准操作之一。我不断收到此错误消息:
Error: { type: 'request-id',
error: { code: 4000, message: 'Invalid or unknown message' } }
当它侦听 websocket 流时,如何判断sharedb
忽略某些不是操作的 websocket 消息?