Websocket client not connecting to server (nodejs)

Viewed 39

I have a NodeJS express app which listens on port 3000. In that app I define a websocket connection like so:

const express = require('express');
const app = express();
const server = require("http").createServer(app);


const WebSocket = require("ws");
const wss = new WebSocket.Server({ server });

wss.on("connection", ws => {
    ws.send("You (the client) connected");
    ws.on("message", msg => {
        ws.send("Server received your msg: " + msg);
    });
});
app.listen(3000, () => {console.log("Listening on port 3000");});

This code is on the NodeJS backend, and it listens for websocket connections. It sends a message to the client when the client connects, and when the client sends a message.

On the font end, I have the following vanilla JavaScript code inside my index.html:

const socket = new WebSocket("ws://my.url.com:3000");

socket.addEventListener("open", evnt => {
    console.log(evnt);
    socket.send("Меssage from client");
});


socket.addEventListener("message", evnt => {
    console.log("Received msg from server:", evnt.data);
});

But my code does not work: when I run the front-end code, the socket object (in the front end) never connects; when I try to call socket.send I get an error:

Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

Eventually the connection times out but the client socket never connects to the socket on the server. How can I fix my code so that the client side can connect successfully?

1 Answers
Related