File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const WebSocket = require ( 'ws' ) ;
2+
3+ // Create a new WebSocket server that listens on port 8080
4+ const wss = new WebSocket . Server ( { port : 8080 } ) ;
5+ // Listen for new connections to the WebSocket server
6+ wss . on ( 'connection' , ( ws ) => {
7+ console . log ( 'Client connected' ) ;
8+ const getRandomYValue = ( ) => Math . floor ( Math . random ( ) * 100 ) + 30 ;
9+
10+ // Send initial data
11+ const initialData = [ ] ;
12+ for ( let i = 0 ; i < 10 ; i ++ ) { // Example: 10 data points
13+ initialData . push ( {
14+ x : new Date ( ) . getTime ( ) - ( 10 - i ) * 1000 , // Earlier timestamps
15+ y : getRandomYValue ( )
16+ } ) ;
17+ }
18+ ws . send ( JSON . stringify ( { initialData } ) ) ;
19+
20+ // Send data updates every second
21+ setInterval ( ( ) => {
22+ const updateData = {
23+ x : new Date ( ) . getTime ( ) ,
24+ y : getRandomYValue ( )
25+ } ;
26+ ws . send ( JSON . stringify ( { updateData } ) ) ;
27+ } , 1000 ) ;
28+
29+ ws . on ( 'close' , ( ) => {
30+ console . log ( 'Client disconnected' ) ;
31+ } ) ;
32+ } ) ;
33+
34+ console . log ( 'WebSocket server is running on ws://localhost:8080' ) ;
You can’t perform that action at this time.
0 commit comments