Sockets

by Johan Vandeplas

HTML

<script src="http://cdn.sencha.com/ext/gpl/4.2.1/ext-all-dev.js"></script>
<link rel="stylesheet" href="http://cdn.sencha.com/ext/gpl/4.2.1/resources/ext-theme-neptune/ext-theme-neptune-all.css">

JavaScript

/**
 * This is an undocumented file.
 * @author Johan Vandeplas
 * @date 1/12/2015
 */

Ext.define('Ceres.util.websocket.Socket', {
    mixins: {
        observable: 'Ext.util.Observable'
    },

    connection: null,

    constructor: function (config) {
        this.mixins.observable.constructor.call(this, config);

        this.addEvents(
            'open',
            'message',
            'close',
            'error');

        this.callParent(arguments);
        this.createConnection();
    },
    createConnection: function () {
        var me = this;
        if (!me.url) {
            throw new Error('No URL');
        }
        if(me.connection && me.connection.readyState === me.connection.OPEN){
            me.connection.close();
        }
        me.connection = new WebSocket(me.url);
        me.attachHandlers(me.connection);
    },
    attachHandlers: function (connection) {
        var me = this;

        connection.onopen = function () {
            me.onOpen.apply(me, arguments);
        };
        connection.onmessage = function () {
            me.onMessage.apply(me, arguments);
        };
        connection.onclose = function () {
            me.onClose.apply(me, arguments);
        };
        connection.onerror = function () {
            me.onError.apply(me, arguments);
        };
        me.on('sendMessage', me.sendMessage);
    },
    onOpen: function (e) {
        this.fireEvent('open', arguments);
        console.info('WebSocket open: ', e);
    },
    onMessage: function (e) {
        this.fireEvent('message', arguments);
        console.log('Server: ', Ext.decode(e.data, true));
    },
    onClose: function (e) {
        this.fireEvent('close', arguments);
        console.info('WebSocket close ', e);
    },
    onError: function (error) {
        this.fireEvent('error', arguments);
        console.error('WebSocket Error ', error);
    },
    open: function (callback, connection) {
        this.connection = connection ||...