dimanche 18 décembre 2016

WebSocket connection raised "Error: not opened" after sending a message

I have the following test which is trying to send a data to the test server with WebSockets:

var Server = require('mock-socket').Server;
var http = require('http');
var expect = require("expect.js");
var SageWsClient = require("../source/client.js");


describe('Test client with echo server', function() {

    var websocket_server = null;

    before(function(done) {
        websocket_server = new Server('ws://127.0.0.1:8080');
        websocket_server.on('message', function(event) {
            websocket_server.send(event.data);
        });

        done();
    });

    after(function(done) {
        websocket_server.stop();
        done();
    });

    describe("sage-ws-client", function() {

        it("should send message in JSON format to the server", function(done) {
            var result = null;
            var router = {"echo": function(response){result = response}};
            var client = new SageWsClient("ws://127.0.0.0:8080", undefined, router);

            var data = {"event": "echo", "key": "value"};
            client.send(client);

            setTimeout(function () {
                expect(result).to.eql(data);
                done();
            }, 2000)
        });
    });
});

SageWsClient don't doing something special, just send a message in JSON format via existing connection:

function SageWsClient(url, event_keyword, router) {
    this.connection = new WebSocket(url);
    this.event_keyword = (typeof event_keyword !== "undefined") ? event_keyword : "event";
    this.router = (typeof router !== "undefined") ? router : {};

    this.connection.onmessage = function(event) {
        var json = JSON.parse(event.data);
        this.router(json[this.event_keyword], json);
    };
}


SageWsClient.prototype.send = function(data) {
    var message = JSON.stringify(data);
    this.connection.send(message);
    return this;
};

When this test is started, it failing with the following error:

1) Test client with echo server sage-ws-client should send message in JSON format to the server:
     Error: not opened
      at WebSocket.send (node_modules/ws/lib/WebSocket.js:219:16)
      at SageWsClient.send (source/client.js:21:21)
      at Context.<anonymous> (tests/client.js:62:20)

The question here is how to fix an issue with a situation when client connection not ready to send a data to a server? I've tried to change used ports, make a timeouts before the method invoke , but the result still the same.

Aucun commentaire:

Enregistrer un commentaire