1+
2+
3+ const uWS = require ( 'uWebSockets.js' ) ;
4+ const port = 9001 ;
5+
6+ const wsc = require ( 'ws' ) ;
7+
8+ const app = uWS . App ( ) . ws ( '/*' , {
9+ /* Options */
10+ maxPayloadLength : 16 * 1024 * 1024 ,
11+ idleTimeout : 10 ,
12+ maxBackpressure : 1024 ,
13+ closeOnBackpressureLimit : true , /* Enable or disable as needed */
14+
15+ /* Handlers */
16+ open : ( ws ) => {
17+ console . log ( "Client connected" ) ;
18+ ws . subscribe ( 'clock_feed' ) ;
19+
20+ /* Disable closeOnBackpressureLimit and see this lie around 1024 */
21+ ws . clock = setInterval ( ( ) => {
22+ console . log ( "Connected socket has " + ws . getBufferedAmount ( ) + " bytes buffered" ) ;
23+ } , 1000 ) ;
24+ } ,
25+ close : ( ws , code , message ) => {
26+ clearInterval ( ws . clock ) ;
27+ console . log ( "Client disconnected: " + code + ", " + message ) ;
28+ /* The library guarantees proper unsubscription at close */
29+ }
30+ } ) . listen ( port , ( listenSocket ) => {
31+ if ( listenSocket ) {
32+ console . log ( 'Listening to port ' + port ) ;
33+ } else {
34+ console . log ( 'Failed to listen to port ' + port ) ;
35+ }
36+ } ) ;
37+
38+ /* Publish the time as fast as possible in a loop */
39+ function sendTime ( ) {
40+ app . publish ( "clock_feed" , Date . now ( ) . toString ( ) ) ;
41+ setImmediate ( sendTime ) ;
42+ }
43+ sendTime ( ) ;
44+
45+ /* Make a connection to the server */
46+ const ws = new wsc . WebSocket ( 'ws://localhost:9001' ) ;
47+ ws . on ( 'message' , function message ( data ) {
48+ console . log ( 'received: %s' , data ) ;
49+
50+ /* If we pause receive, we will become slow receiver */
51+ console . log ( "Will become slow receiver" ) ;
52+ ws . _socket . pause ( ) ;
53+ } ) ;
0 commit comments