简体   繁体   中英

Websocket client not connecting to server (nodejs)

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?

You can change app.listen to server.listen. it may be work. Or You can do above using socket.io Refer following repository index.js file. https://github.com/yasiruRathnayaka97/pdfLibrest/blob/master/index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM