Sunday, 30 April 2017

JavaScript WebSocket OnOpen not called

I can't seem to get this WebSocket connection working. Here is my server:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const WSServer = require('uws');
app.use(express.static('./client'));
var wss = new WSServer({ http });
const port = 4007;
wss.on('connection', (socket)=> {
  socket.send("Bonjour");
  socket.on('message', parser);
});
function parser(message) {
  message = JSON.parse(message);
  console.log(message[0]);
}
http.on("upgrade", () => { wss.handleUpgrade });
http.listen(port, () => {

On my server, the "connection" event is never triggered. Here is my client:

var socket = new WebSocket(window.location.origin.replace(/https?/g, "ws"));
var data = ["hello"];
socket.onopen = function() {
    socket.send(JSON.stringify(data));
};
socket.onmessage = function(message) {
    alert(message);
    return false;
};

The client never receives "Bonjour", the onopen function is never triggered, and if I attempt to send a message outside of the onopen function, I get this error:

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

Any help will be appreciated.



via Eli R

No comments:

Post a Comment