I am starting to use NodeJS and Socket.IO. I am trying to set up a basic example with a NodeJS http server and establish a Socket.IO connection to the server.
I am also using angular JS and basically what I want is that when a user presses a button then the connection to the server is established. However, when I try it I get this error
GET http://localhost/socket.io/?EIO=2&transport=polling&t=1404288173776-3 net::ERR_CONNECTION_REFUSED
Here is my code:
server.js
var http = require('http'); var server= http.createServer(handler); var io = require('socket.io')(server); server.listen(8080); function handler(req, res) { res.writeHead(200); res.end('Hello Http'); } io.on('connection', function (socket){ socket.emit('news', { hello: 'world' }); console.log('connected!'); });
app.js
var app = angular.module('testApp', ['ngRoute']); app.controller('TestCtrl', function ($scope){ $scope.msg= ""; $scope.try = function (){ $scope.msg= "ALO" var socket = io('http://localhost'); socket.on('news', function (data) { console.log(data); }); }; });
And on my test.html file:
<body ng-controller="TestCtrl"> <h2>{{msg}}</h2> <button ng-click="try()">Try</button> <script src="../js/angular.min.js"></script> <script src="../js/angular-route.min.js"></script> <script src="../js/app.js"></script> <script src="../node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script> <!-- <script src="/socket.io/socket.io.js"></script> --> </body>
I think that the error might be something related to the path I use when including the socket.io.js I have tried also using directly localhost:8080 in the path because I read it could be a solution but that didn't work. So please, I appreciate any help given. Thanks!
First and foremost, please note that disconnections are common and expected, even on a stable Internet connection: anything between the user and the Socket.IO server may encounter a temporary failure or be restarted.
Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.
In the first case, the Socket will automatically try to reconnect, after a given delay.
I faced exactly the same issue. I did not see the ERR_CONNECTION_REFUSED in socket.io@~0.9. The error surfaced after I upgraded socket.io to 1.3.
I solved it by simply removing the URL from the client side constructor:
Change
var socket = io('http://localhost');
To
var socket = io();
As the socket.io tutorial showed: http://socket.io/get-started/chat/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With