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.
CodePudding user response:
I suggested to you check the oroginal documentation. Here is the Link
https://github.com/theturtle32/WebSocket-Node
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
good luck :)
CodePudding user response:
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)
})
})