nodejsj
nodejsj

Reputation: 555

connecting to socket.io server doesn't work when it's via Websocket()

This code works great and connects to the socket server that I have running:

 var socket = io('http://localhost:8888');
  socket.on('news', function (data) {
    console.log(data);

    socket.emit('evento', { my: 'data' });
  });
socket.on('disconnect', function () {
   console.log('user disconnected');
  });
socket.on('connect', function () {
   console.log('user connect');
var data = 'ddsds';
       socket.emit('evento', { my: 'data' });


  });

On the other hand when I try to use WebSocket() it fails to connect. This is the code that doesn't work:

var socket = new WebSocket('ws://localhost:8888');
// Open the socket
socket.onopen = function(event) {

    // Send an initial message
    socket.send('I am the client and Im listening!');

}

    // Listen for messages
    socket.onmessage = function(event) {
        console.log('Client received a message',event);
    };

    // Listen for socket closes
    socket.onclose = function(event) {
        console.log('Client notified socket has closed',event);
    };
    socket.onerror = function(event) {
        console.log('error: ',event);
    };

It's not an error in the code; I think there is a different way to connect. I need this to work using WebSocket();. Any help would be greatly appreciated!!

Upvotes: 0

Views: 609

Answers (1)

jfriend00
jfriend00

Reputation: 707328

socket.io is something that runs on top of WebSocket (using WebSocket as one of the transports it supports). It adds new semantics on top of WebSocket so you can't use the socket.io methods and events directly with a WebSocket object.

socket.io will select the WebSocket transport if it is available so you should not need to use your second example - the first should work just fine and will use WebSockets automatically (when available).

See this answer and this answer for how to use the minimized, gzipped and cached version of socket.io which makes it smaller and faster.

Upvotes: 1

Related Questions