0

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!!

hunch_hunch
  • 2,283
  • 1
  • 21
  • 26
nodejsj
  • 535
  • 1
  • 5
  • 14

1 Answers1

1

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.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • yeah the issue is socket.io is ~60kb, and use websockets directly will save well about 60kb. On the server side I like running socket.io. site gets over 2000 concurrent or more throughout the day and we try to make the pages load as fast as we can. – nodejsj Oct 03 '14 at 19:06
  • @stacknoob - You should switch to the minimized version of socket.io which is smaller: http://stackoverflow.com/a/9015260/816620. No matter what your issue is, you can't use the socket.io interface with just a plain WebSocket and none of the socket.io code. – jfriend00 Oct 03 '14 at 19:13
  • @stacknoob - per http://stackoverflow.com/a/14589826/816620, you can also enable gzip and browser caching. With minification and these two enabled, it's a lot lot smaller. – jfriend00 Oct 03 '14 at 19:20
  • thanks jfriend00.I am using the minified one. but yeah I ended up using socket.io client as per your advice – nodejsj Oct 03 '14 at 19:49