Skip to content

Latest commit

 

History

History
58 lines (41 loc) · 2.29 KB

debugging.md

File metadata and controls

58 lines (41 loc) · 2.29 KB

Debugging WebSocket

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.

WebSocket debugger

Debugging the server

  1. Create a directory named testWebSocket and change to that directory.

  2. Run npm init -y.

  3. Run npm install ws.

  4. 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');
    });
  5. Set breakpoints on the ws.send lines so you can inspect the code executing.

  6. Start debugging by pressing F5. The first time you may need to choose Node.js as the debugger.

WebSocket server debugging

Debugging the client

  1. Open the Chrome debugger by pressing F12.

  2. 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);
    };
  3. Select the Network tab and then select the HTTP message that was generated by the execution of the above client code.

  4. With the HTTP message selected, you then click the Messages tab to view the WebSocket messages

  5. 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');
  6. You should see the messages in the Messages debugger window.

  7. Send some more messages and observe the communication back and forth without stopping on the breakpoints.

WebSocket client debugging