You can debug both sides of the WebSocket communication with VS Code to debug the server, and Chrome to debug the client. When you do this you will notice that Chrome's debugger has support specifically for working with WebSocket communication.
-
Create a directory named
testWebSocketand change to that directory. -
Run
npm init -y. -
Run
npm install ws. -
Open VS Code and create a file named
main.js. Paste the following code.const { WebSocketServer } = require('ws'); const wss = new WebSocketServer({ port: 3000 }); wss.on('connection', (ws) => { ws.on('message', (data) => { const msg = String.fromCharCode(...data); console.log('received: %s', msg); ws.send(`I heard you say "${msg}"`); }); ws.send('Hello webSocket'); });
-
Set breakpoints on the
ws.sendlines so you can inspect the code executing. -
Start debugging by pressing
F5. The first time you may need to choose Node.js as the debugger.
-
Open a Chrome browser, point it at
localhost:3000and then open the debugger by pressingF12. -
Paste this code into the debugger console window and press enter to execute it. Executing this code will immediately hit the server breakpoint. Take a look at what is going on and then remove the breakpoint from the server.
const protocol = window.location.protocol === 'http:' ? 'ws' : 'wss'; const socket = new WebSocket(`${protocol}://${window.location.host}`); socket.onmessage = (event) => { console.log('received: ', event.data); };
-
Select the
Networktab and then select the HTTP message that was generated by the execution of the above client code. -
With the HTTP message selected, you then click the
Messagestab to view the WebSocket messages -
Send a message to the server by executing the following in the debugger console window. This will cause the second server breakpoint to hit. Explore and then remove the breakpoint from the server.
socket.send('I am listening');
-
You should see the messages in the
Messagesdebugger window. -
Send some more messages and observe the communication back and forth without stopping on the breakpoints.


