Created
April 29, 2017 08:53
-
-
Save SarasArya/111092af8d435f850856c62e1bb36751 to your computer and use it in GitHub Desktop.
Socket.io NodeJS and AngularJS clients demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//On instruction of how to debug if sockets are working or not. Please check here https://socket.io/docs/logging-and-debugging/ | |
//NodeJS Side | |
const server = require('http').Server(app), | |
io = require('socket.io')(server); | |
io.sockets.on('connection', function (socket) { | |
socket.on('set', function (status, callback) { | |
console.log(status); | |
callback('ok'); | |
}); | |
}); | |
//Angular JS Side | |
//After you have bower installed the socket.io-client dependency. In your app.js, create a factory of socket methods. | |
app.factory('socket', function($rootScope) { | |
// let socket = io.connect('https://api.example.com'); //in production | |
const socket = io.connect('http://localhost:3040'); //in development | |
return { | |
on: function(eventName, callback) { | |
socket.on(eventName, function() { | |
var args = arguments; | |
$rootScope.$apply(function() { | |
callback.apply(socket, args); | |
}); | |
}); | |
}, | |
emit: function(eventName, data, callback) { | |
socket.emit(eventName, data, function() { | |
var args = arguments; | |
$rootScope.$apply(function() { | |
if (callback) { | |
callback.apply(socket, args); | |
} | |
}); | |
}); | |
} | |
}; | |
}); | |
//Dependency inject this into any controller and type their. | |
socket.emit('set', 'is_it_ok', function(response) { | |
console.log(response); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment