summaryrefslogtreecommitdiff
path: root/node_modules/socket.io/support/node-websocket-client/test/test-basic.js
blob: f0104248031a0d1bc7d7ae3e5ff7b33669349429 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Verify that we can connect to a WebSocket server, exchange messages, and
// shut down cleanly.

var assert = require('assert');
var WebSocket = require('../lib/websocket').WebSocket;
var WebSocketServer = require('websocket-server/ws/server').Server;

var PORT = 1024 + Math.floor(Math.random() * 4096);
var C_MSG = 'Client test: ' + (Math.random() * 100);
var S_MSG = 'Server test: ' + (Math.random() * 100);

var serverGotConnection = false;
var clientGotOpen = false;
var clientGotData = false;
var clientGotMessage = false;
var serverGotMessage = false;
var serverGotClose = false;
var clientGotClose = false;

var wss = new WebSocketServer();
wss.listen(PORT, 'localhost');
wss.on('connection', function(c) {
    serverGotConnection = true;

    c.on('message', function(m) {
        assert.equal(m, C_MSG);
        serverGotMessage = true;

        c.close();
    });

    c.on('close', function() {
        serverGotClose = true;
        wss.close();
    });

    c.write(S_MSG);
});

var ws = new WebSocket('ws://localhost:' + PORT + '/', 'biff');
ws.on('open', function() {
    clientGotOpen = true;
});
ws.on('data', function(buf) {
    assert.equal(typeof buf, 'object');
    assert.equal(buf.toString('utf8'), S_MSG);

    clientGotData = true;

    ws.send(C_MSG);
});
ws.onmessage = function(m) {
    assert.deepEqual(m, {data : S_MSG});
    clientGotMessage = true;
};
ws.onclose = function() {
    clientGotClose = true;
};

process.on('exit', function() {
    assert.ok(serverGotConnection);
    assert.ok(clientGotOpen);
    assert.ok(clientGotData);
    assert.ok(clientGotMessage);
    assert.ok(serverGotMessage);
    assert.ok(serverGotClose);
    assert.ok(clientGotClose);
});