Skip to content

Instantly share code, notes, and snippets.

@yangboz
Created December 15, 2014 02:59
Show Gist options
  • Select an option

  • Save yangboz/c01de964c5f5bc7e53c5 to your computer and use it in GitHub Desktop.

Select an option

Save yangboz/c01de964c5f5bc7e53c5 to your computer and use it in GitHub Desktop.

Revisions

  1. yangboz created this gist Dec 15, 2014.
    55 changes: 55 additions & 0 deletions AngularJS+WebSocket
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    //WebSocket
    .factory('WebsocketService', ['$rootScope', '$timeout', function ($rootScope, $timeout) {

    var _ws;
    var _username = '';
    var messages = [];
    var users = [];

    function onMessage(e) {
    var data = JSON.parse(decodeURIComponent(e.data));
    $rootScope.$apply(function () {

    if (data.type === 'users') {
    users = data.message;
    $rootScope.$broadcast('websocket', 'users', users);
    return;
    }

    messages.splice(0, 0, {user: data.user, message: data.message, date: data.date});
    $rootScope.$broadcast('websocket', 'message', messages);
    });
    }

    return {

    login: function (url, username) {

    _username = username;

    _ws = new WebSocket(url);
    _ws.onmessage = onMessage;
    _ws.onopen = function () {
    _ws.send(encodeURIComponent(JSON.stringify({type: 'change', message: _username})));
    };

    },

    logoff: function () {
    _ws.close();
    _ws = null;
    _username = '';
    users = [];
    $rootScope.$broadcast('websocket', 'users', users);
    },

    send: function (message) {
    _ws.send(encodeURIComponent(JSON.stringify({type: 'message', message: message})));
    //
    _ws.onmessage = function (message) {
    console.log("_ws.onmessage:", message);
    }
    }
    };

    }])