Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save krainet/cd44f899b30956e2058589f3b9c61772 to your computer and use it in GitHub Desktop.
Save krainet/cd44f899b30956e2058589f3b9c61772 to your computer and use it in GitHub Desktop.
//Without AngularJS
//Include socket.io library to your JS app
//Sample: <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.5.1/socket.io.js"></script>
//Instantiate global var socket.
var socket = io();
//Subscribe to stream
var action = 'subscribe';
var data = {
'streamId':'stream_id',
'token':'tokenj31lj3l12kl31kl23l1j23l',
};
socket.emit(action,data,function(respData){
});
//Unsubscribe to stream
var action = 'unsubscribe';
var data = {
'streamId':'stream_id',
'token':'tokenj31lj3l12kl31kl23l1j23l',
};
socket.emit(action,data,function(respData){
});
//Get stream data
var eventName = 'notif';
socket.emit(eventName,function(streamMsg){
console.log(streamMsg);
});
//more info at :
//https://socket.io/get-started/chat/
//With AngularJS
//Simple angularJS service module
/**
* Created by ramon on 1/11/16.
*/
/*
* Sockets Service
*/
angular.module('socketService', [])
.factory('socketService', ['$rootScope','$q',
function ($rootScope,$q) {
var socket = io.connect(SERVER_URL+'/', { forceNew: true });
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);
}
});
});
}
};
}]);
----------------------
//Using service
//Subscribing to streams:
var subsData = {
'streamId':'stream_id',
'token':'tokenj31lj3l12kl31kl23l1j23l',
};
socketService.emit('subscribe',subsData, function(afectedSubscriptions){
//recomended to save an array of strema to make unsubscribe later
console.log('Afected streamIds');
console.log(afectedSubscriptions);
});
//Unsubscribe
angular.forEach(arrayOfStreamIds,function(value,key){
socketService.emit('unsubscribe',{'streamId':value},function(resp){
console.log('Unsubscribe id '+value);
});
});
//Reading data from streams:
socketService.on('notif',function(data){
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment