PageRenderTime 303ms CodeModel.GetById 181ms app.highlight 6ms RepoModel.GetById 115ms app.codeStats 0ms

/js/lib/Socket.IO-node/support/node-websocket-client/test/test-basic.js

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
JavaScript | 63 lines | 50 code | 11 blank | 2 comment | 0 complexity | 8591d37d73ea9e461d72d9634b4d6802 MD5 | raw file
 1// Verify that we can connect to a WebSocket server, exchange messages, and
 2// shut down cleanly.
 3
 4var assert = require('assert');
 5var WebSocket = require('../lib/websocket').WebSocket;
 6var WebSocketServer = require('websocket-server/ws').Server;
 7
 8var PORT = 1024 + Math.floor(Math.random() * 4096);
 9var C_MSG = 'Client test: ' + (Math.random() * 100);
10var S_MSG = 'Server test: ' + (Math.random() * 100);
11
12var serverGotConnection = false;
13var clientGotOpen = false;
14var clientGotData = false;
15var clientGotMessage = false;
16var serverGotMessage = false;
17var serverGotClose = false;
18
19var wss = new WebSocketServer();
20wss.listen(PORT, 'localhost');
21wss.addListener('connection', function(c) {
22    serverGotConnection = true;
23
24    c.write(S_MSG);
25
26    c.addListener('message', function(m) {
27        assert.equal(m, C_MSG);
28        serverGotMessage = true;
29    });
30
31    c.addListener('close', function() {
32        serverGotClose = true;
33        wss.close();
34    });
35});
36
37var ws = new WebSocket('ws://localhost:' + PORT + '/', 'biff');
38ws.addListener('open', function() {
39    clientGotOpen = true;
40});
41ws.addListener('data', function(buf) {
42    assert.equal(typeof buf, 'object');
43    assert.equal(buf.toString('utf8'), S_MSG);
44
45    clientGotData = true;
46
47    ws.send(C_MSG);
48    ws.close();
49});
50ws.onmessage = function(m) {
51    assert.equal(m, S_MSG);
52    assert.equal(typeof m, 'string');
53    clientGotMessage = true;
54};
55
56process.addListener('exit', function() {
57    assert.ok(serverGotConnection);
58    assert.ok(clientGotOpen);
59    assert.ok(clientGotData);
60    assert.ok(clientGotMessage);
61    assert.ok(serverGotMessage);
62    assert.ok(serverGotClose);
63});