1- 'use strict'
1+ const debug = require ( 'debug' ) ( 'dataparty.comms.websocket' )
22
3- const debug = require ( 'debug' ) ( 'dataparty.comms.websocketcomms' )
4- const W3CWebSocket = require ( 'websocket' ) . w3cwebsocket ;
5- const WebSocket = W3CWebSocket
3+ const WebSocket = require ( 'ws' )
4+ const EventEmitter = require ( 'eventemitter3' )
65
7- const SocketComms = require ( './socket-comms' )
86
9- class WebsocketComms extends SocketComms {
10- constructor ( { session, uri, identity, remoteIdentity} ) {
11- super ( { session, uri, identity, remoteIdentity} )
7+ const PeerComms = require ( './peer-comms' )
128
13- this . socket = new WebSocket ( this . uri )
14- this . socket . onclose = this . onclose . bind ( this )
15- this . socket . onopen = this . onopen . bind ( this )
16- this . socket . onmessage = this . onmessage . bind ( this )
9+
10+ class WebsocketShim extends EventEmitter {
11+ constructor ( conn ) {
12+ super ( )
13+ this . conn = conn
14+
15+ this . conn . onmessage = ( evt ) => {
16+ this . emit ( 'data' , evt . data )
17+ }
18+
19+ this . conn . onopen = ( ) => {
20+ debug ( 'shim open' )
21+ this . emit ( 'connect' )
22+ }
23+
24+ this . conn . onclose = ( ) => {
25+ this . emit ( 'close' )
26+ }
27+
28+ this . conn . onerror = ( err ) => {
29+ this . emit ( 'error' , err )
30+ }
31+
32+ if ( this . conn . readyState == WebSocket . OPEN ) {
33+ setTimeout ( ( ) => { this . emit ( 'connect' ) } , 1 )
34+ }
35+
36+ debug ( 'connection shim' , this . conn . readyState )
37+ }
38+
39+ close ( ) {
40+ this . conn . close ( )
41+ }
42+
43+ destroy ( ) {
44+ this . conn . terminate ( )
45+ }
46+
47+ send ( val ) { this . conn . send ( val ) }
48+
49+ }
50+
51+ class WebsocketComms extends PeerComms {
52+ constructor ( { uri, connection, remoteIdentity, host, party, ...options } ) {
53+ super ( { remoteIdentity, host, party, ...options } )
54+
55+ this . uri = uri
56+ this . connection = connection
57+
58+ if ( this . host && ! this . connection ) {
59+ throw new Error ( 'existing connection expected' )
60+ }
61+
62+ if ( ! this . host && ( ! this . uri && ! this . connection ) ) {
63+ throw new Error ( 'uri or existing connection expected' )
64+ }
65+ }
66+
67+
68+ async socketInit ( ) {
69+ debug ( 'init' )
70+
71+ if ( ! this . host && ! this . connection ) {
72+ debug ( 'opening client connection to' , this . uri )
73+ this . connection = new WebSocket ( this . uri )
1774 }
75+
76+ this . socket = new WebsocketShim ( this . connection )
77+ }
1878}
1979
80+
2081module . exports = WebsocketComms
0 commit comments