I'm trying to integrate Socket.io with Angular, and I'm having difficulty connecting from the client side to the server. I looked at other related questions, but my problem happens locally, so there is no web server in the middle.
This code of my server is as follows:
const app = express(); const server = http.createServer(app); const io = require('socket.io').listen(server); io.on('connection', function(socket) { socket.emit('greet', { hello: 'Hey, Mr.Client!' }); socket.on('respond', function(data) { console.log(data); }); socket.on('disconnect', function() { console.log('Socket disconnected'); }); });
I load client side JavaScript files using Grunt in the following order:
dist: { src: [ public/bower_components/angular/angular.min.js, ... public/bower_components/socket.io-client/dist/socket.io.min.js, public/bower_components/angular-socket-io/socket.min.js, ... ] }
Then in my controller:
function MyController($scope) { let socket = io.connect(window.location.href); socket.connect('http://localhost:3000'); socket.on('greet', function(data) { console.log(data); socket.emit('respond', { message: 'Hello to you too, Mr.Server!' }); }); ... }
Before using the btford/angular-socket-io
library, I want to make sure that I can establish the connection correctly, but I get the following error in the console:
Interestingly, if I restart the Node.js server process, it will be able to send a message, but using a poll instead of websites.
I tried all sorts of options in a socket.connect call, but nothing worked.
Any help would be appreciated.
UPDATE (12/30/2016):
I just realized that websockets works partially. I see a 101 Switching Protocols request in the Chrome Developer Console. However, the only frames that I see there are engine.io protocol packets (ping, pong). However, my application socket messages are still returning to polling for some reason ...