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
testWebSocket
and 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: 9900 }); 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.send
lines 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 the Chrome debugger by pressing
F12
. -
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 socket = new WebSocket('ws://localhost:9900'); socket.onmessage = (event) => { console.log('received: ', event.data); };
-
Select the
Network
tab 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
Messages
tab 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
Messages
debugger window. -
Send some more messages and observe the communication back and forth without stopping on the breakpoints.