-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.js
More file actions
86 lines (69 loc) · 2.83 KB
/
client.js
File metadata and controls
86 lines (69 loc) · 2.83 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { Client, BinaryEncoder, UInt8Codec, UIntLongCodec, Int16Codec, BooleanCodec, StringLongCodec } from 'netcode/client';
window.addEventListener('load', () => {
const target = document.getElementById('output');
const { info } = console;
console.info = (message, ...subst) => {
info(message, ...subst);
subst.forEach(sub => message = message.replace('%s', sub));
const time = Date.now() - start;
output.innerText += `▸ ${time}ms | ${message}\n`;
}
// Register your events
const encoder = new BinaryEncoder([
['id', new UInt8Codec()],
['ping', new UIntLongCodec(6)],
['pong', new UIntLongCodec(6)],
['inverse', new BooleanCodec()],
['greeting', new StringLongCodec()],
['total', new UInt8Codec()],
['int16', new Int16Codec()],
]);
const server = 'ws://127.0.0.1:8002';
const start = Date.now();
console.info('Connecting to %s', server)
// Create the client
const client = new Client(server, encoder);
let ping;
// Listen for a "pong" event
client.on('pong', ({ detail: pong }) => {
console.info('pong: %s ms (%s - %s)', pong - ping, pong, ping);
});
// Listen for an "id" event
client.on('id', ({ detail: id }) => {
console.info('connected with id %s', id);
ping = Date.now();
console.info('sending ping: %s', ping);
// Send a "ping" event
client.send('ping', ping);
});
// Listen for a "total" event
client.on('total', ({ detail: total }) => {
console.info(`There is ${total} people connected.`);
});
// Listen for a "int16" event
client.on('int16', ({ detail: value }) => {
console.info(`int16 codec: ${value}.`);
client.send('int16', -32768);
});
// Listen for an "inverse" event
client.on('inverse', ({ detail: status }) => {
// Answer with an "inverse" event
client.send('inverse', !status);
console.info('Inverse received: %s', status);
// Send a "greeting" event
client.send('greeting', 'Hello, I\'m client 😊! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut imperdiet molestie libero, ut sollicitudin tortor dignissim quis. Nulla iaculis nisi turpis, a malesuada nibh faucibus a. Nunc tellus lorem, varius sit amet tellus eu, dictum consectetur nulla.');
});
// Listen for a "greeting" event
client.on('greeting', ({ detail: message }) => {
console.info('Servers geets you: "%s"', message);
});
// Listen for oppening connection
client.on('open', () => {
console.info('Connection open.');
setTimeout(() => client.close(1000, 'All good :)'), 10 * 1000);
});
// Listen for connection close
client.on('close', (data) => {
console.info('Connection closed.', data);
});
});