0

I am attempting to connect to a node.js server via a web socket. The difficulty I am having is that my node server does not serve my web pages. From looking at it I think socket.io assumes that the server will be serving the pages so I can't use 90% of the examples out there (or at least I haven't figured out how to). I am trying to get this simple demo page to connect but am always getting connection refused.

<html>
<head>
    <title>Title</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        var ws = new WebSocket("ws://my-devbox.local");
    </script>

</head>
<body>
    <button id="myButton">Click Me Mo Fool!!!</button>
</body>

In my app.js I have the following (with extraneous information omitted)

var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    console.log('A new user connected!');
    //socket.emit('info', { msg: 'Hello World' });
});

Thanks

ed209
  • 828
  • 2
  • 14
  • 30
  • Take a look at http://stackoverflow.com/questions/22232023/can-i-use-socket-io-client-to-connect-to-a-standard-websocket/22235945 - you need to decide whether you want to do raw WebSockets or socket.io. – Aaron Dufour Dec 17 '14 at 16:57

1 Answers1

1

There are a couple issues here. First socket.io is not a plain WebSocket. If you use socket.io on the server-side, then you need to use socket.io on the client side. It has its own protocol on top of webSocket so you must use it on both ends of the connection.

Second, socket.io (and any webSocket connection) initiates its connection via an http request. That means it is limited by the same-origin policy (can't connect to origins other than the one that your web page came from). So, you will need to be connecting to a server that has enabled cross origin connections if you want to connect to an origin other than the one serving the web page. Enabling cross origin connections for socket.io is easily done by just doing this on your server:

io.set('origins', '*:*');

More about enabling cross origin requests here: Socket.io + Node.js Cross-Origin Request Blocked and here: how to set socket.io origins to restrict connections to one url

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thank you... at least this gives me a start. The question this brings up for me is if including socket.io directly (not via the server) will work. Nobody seems to be doing it that way and I'm wondering what the implications are? – ed209 Dec 17 '14 at 16:58
  • @ed209 - Yes, you can include `socket.io` directly. Including it via the `socket.io` server is just a convenience that automatically keeps the client/server versions in sync for you. But, you can include the client from anywhere as long as you make sure the client and server version numbers are compatible. – jfriend00 Dec 17 '14 at 17:12