如何测试使用JavaScript开发的WebSocket

时间:2015-08-19 13:45:28

标签: javascript java angularjs sockets websocket

我创建了WebSocket.js,但遗憾的是由于数据不可用,我无法对其进行测试。要求是来自各种来源的数据,所以我有多个套接字。注意:我想特别测试我的socket.onMessage表现为不同的套接字。请在下面找到代码段:

var webSocket;
var txQueue = [];
var defaultReconnectTimeout = 1000; //will be multiplied by 2 and saved into reconnectTimeout on each try
var reconnectTimeout = defaultReconnectTimeout;

var registerWebSocketHandlers = function(webSocket) {
    webSocket.onclose = function(){
        setTimeout(service.reopen, reconnectTimeout *= 2);
    };

    webSocket.onopen = function(e) {
        reconnectTimeout = defaultReconnectTimeout; //reset this
        deferredSend();
    };

    webSocket.onerror = function(e) {
        throw new Error("[WebSocket] An error occured " + e);
    };
}

var uniqid = function() {
    return (new Date().getTime()).toString(16);
}


var deferredSend = function() {
    if(!service.isOpen()) {
        $timeout(deferredSend, 100);
        return;
    }
    while(txQueue.length && service.isOpen()) {
        var payload = txQueue.shift();
        webSocket.send(typeof payload === 'string' ? payload : JSON.stringify(payload));
    }
};

var createNewWebSocketInstance = function(apiUrl){
    var websocket = new $window.WebSocket(apiUrl);
    websocket.id = uniqid();
    return websocket;
}

// TODO: this is a bit hacky since we directly bind it to the raw window event
$window.onbeforeunload = function(e) {
    service.close();
};

var service = {};

service.setMessageEventHandler = function(name,cb) {
    instances[name].onmessage = function(msg) {
        if(msg.data.indexOf('Status: connected') === 0)
        {
            return;
        }

        var jsonObj = JSON.parse(msg.data);
        cb(jsonObj);
    };
};

service.isOpen = function() {
    return webSocket.readyState === 1;
};

service.send = function(msg) {
    txQueue.push(msg);
    deferredSend();
};

service.close = function() {
    return webSocket.close();
};

service.reopen = function() {
    // get old message handler
    var msgHandler = webSocket.onmessage;

    // try closing the previous WebSocket
    service.close();

    // open new WebSocket
    openConnection();

    // re-attach old handler to new WebSocket
    webSocket.onmessage = msgHandler;
};

service.getId = function() {
    return webSocket.id;
}

// Returns an already existing instance of the socket, if unavailable then creates a new one.      
service.getInstance = function(name, config) {
    if(!(name in instances)) {
        instances[name] = createNewWebSocketInstance(config);
    } 
    registerWebSocketHandlers(instances[name]);
    return instances[name];
};

return service;

1 个答案:

答案 0 :(得分:0)

您可以使用websocket.org Echo Test Creating your own test

上的WebSocket来测试websocket.html
  

使用文本编辑器复制以下代码并将其另存为    websocket.html 在硬盘上的某个地方。然后只需在浏览器中打开它。该页面将自动连接,发送消息,   显示响应,然后关闭连接。

请参阅Linux - WebSocket test error