1
votes

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!

1

1 Answers

0
votes

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