简体   繁体   中英

Javascript WebSocket server not receiving messages

I have made a very simple WebSocket app to learn the basics, I've had some success but I've encountered a problem that I can't seem to resolve, mainly since I'm not getting any errors.

Client:

const url = 'ws://localhost:1720';
const ws = new WebSocket(url);

$("#sendbtn").click(function() {
    console.log("clicked");
    var input = $('#messageinput').val();
    ws.send(input);
});

Server:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 1720 });

wss.on('connection', function(ws) {
   console.log("New connection"); 
});

wss.onmessage = function(event) {
  console.log("WebSocket message received:", event);
};

The server successfully logs "New connection" when I open the browser window, but when I try to send a message to the server through button #sendbtn, nothing happens in the server, it doesn't log the message.

I am running it straight from the files API, ie not on XAMPP, could that be the issue here? Thanks for any advice!

how about you try example shown in doc.

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

event is ws object in your code

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