-2

I just follow the tutorial in https://youtu.be/FduLSXEHLng?t=302, as below

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8082 });

wss.on("connection", ws => {
    console.log("New client connected");

    ws.on("close", () => {
        console.log("Client has disconnected!")
    })
})

When I run it with node index.js, it seems to just end immediately (i.e. back to the prompt).

Anything wrong from my end? How can I check what terminate it? (or is it not terminated, but just the prompt showing?)

Sorry, I'm new to node.js and ws. Any guide on how can I debug from there will be great!

** Update ** After adding console.log("Hello");

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8082 });

console.log("Hello");

wss.on("connection", ws => {
    console.log("New client connected");

    ws.on("close", () => {
        console.log("Client has disconnected!")
    })
})

Then it seems to stay there.

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

0

Your implementation is correct and worked for me. I've tested it with a client and it's connected nicely.

To realize the cause of onclose and onerror methods with the WebSocket, you can pass an event parameter to the callback function and log it out.

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8082 });

console.log("Hello");

wss.on("connection", ws => {
    console.log("New client connected");

    ws.on("close", (event) => {
        console.log("Websocket on close", event)
    })

    ws.on("error", (event) => {
        console.log("Websocket on error", event)
    })
})
nima
  • 7,796
  • 12
  • 36
  • 53
  • since your implementation is correct and the error might be with other parts of your application, this is not really an answer to your question, but it helps you to figure out the error event – nima Oct 21 '21 at 12:48
  • Thanks. With `console.log("Hello");`, it works for me too. Just strange that without `console.log("Hello");`, it does work. Can you try without `console.log("Hello");` and see if it works? – Elye Oct 22 '21 at 01:47
  • Hi, Is the problem solved? @Elye – nima Nov 18 '21 at 09:29