rolling websocketjson stream in

This commit is contained in:
Steve Oney
2018-08-13 14:00:37 -04:00
parent 7a69e7533d
commit 3c0af23842
2 changed files with 25 additions and 27 deletions
+25 -1
View File
@@ -2,7 +2,31 @@
import * as ShareDB from 'sharedb';
import * as http from 'http';
import * as WebSocket from 'ws';
import { WebSocketJSONStream } from './websocketJSONStream';
import {Duplex} from 'stream';
//Adapted from https://github.com/avital/websocket-json-stream
class WebSocketJSONStream extends Duplex {
constructor(private readonly ws:WebSocket) {
super({objectMode: true});
this.ws.on('message', (msg: string) => {
this.push(JSON.parse(msg))
});
this.ws.on('close', () => {
this.push(null); // end readable stream
this.end(); // end writable stream
this.emit('close');
this.emit('end');
});
this.on('error', function() { ws.close(); });
this.on('end', function() { ws.close(); });
};
public _read():void {};
public _write(msg:any, encoding:string, next:Function):void {
this.ws.send(JSON.stringify(msg));
next();
};
};
const backend = new ShareDB();
const connection = backend.connect();
-26
View File
@@ -1,26 +0,0 @@
import {Duplex} from 'stream';
import * as WebSocket from 'ws';
//Adapted from https://github.com/avital/websocket-json-stream
export class WebSocketJSONStream extends Duplex {
constructor(private readonly ws:WebSocket) {
super({objectMode: true});
this.ws.on('message', (msg: string) => {
this.push(JSON.parse(msg))
});
this.ws.on('close', () => {
this.push(null); // end readable stream
this.end(); // end writable stream
this.emit('close');
this.emit('end');
});
this.on('error', function() { ws.close(); });
this.on('end', function() { ws.close(); });
};
public _read():void {};
public _write(msg:any, encoding:string, next:Function):void {
this.ws.send(JSON.stringify(msg));
next();
};
};