This repository has been archived by the owner on Aug 18, 2020. It is now read-only.
/
echo.js
84 lines (72 loc) · 2.19 KB
/
echo.js
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
'use strict'
// **Github:** https://github.com/fidm/quic
//
// **License:** MIT
// node example/echo.js
// NODE_DEBUG=quic,quic:session,quic:stream node example/echo.js
require('ts-node/register')
const ilog = require('ilog')
const thunk = require('thunks').thunk
const {
Server,
Client
} = require('../src')
// ---------- Server ----------
const server = new Server()
server
.on('error', (err) => ilog.error(Object.assign(err, { class: 'server error' })))
.on('session', (session) => {
// ilog.info(session)
session
.on('error', (err) => ilog.error(Object.assign(err, { class: 'server session error' })))
.on('stream', (stream) => {
// ilog.info(stream)
stream
.on('error', (err) => ilog.error(Object.assign(err, { class: 'server stream error' })))
.on('data', (data) => {
ilog.info(`server stream ${stream.id} data: ${data.toString()}`)
stream.write(data)
})
.on('end', () => {
ilog.info(`server stream ${stream.id} ended`)
stream.end()
})
.on('finish', () => {
ilog.info(`server stream ${stream.id} finished`)
})
})
})
server.listen(2345)
.then(() => {
ilog.info(Object.assign({ class: 'server listen' }, server.address()))
})
.catch(ilog.error)
// ---------- Client ----------
const cli = new Client()
cli.on('error', (err) => ilog.error(Object.assign(err, { class: 'client error' })))
thunk(function * () {
yield cli.connect(2345)
yield cli.ping()
const stream = cli.request()
stream
.on('error', (err) => ilog.error(Object.assign(err, { class: 'client stream error' })))
.on('data', (data) => {
ilog.info(`client stream ${stream.id} data: ${data.toString()}`)
})
.on('end', () => {
ilog.info(`client stream ${stream.id} ended`)
cli.close()
})
.on('finish', () => {
ilog.info(`client stream ${stream.id} finished`)
})
yield (done) => stream.write('hello, QUIC', done)
let i = 0
while (i <= 99) {
yield thunk.delay(100)
yield (done) => stream.write(`${i++}`, done)
}
stream.end()
yield (done) => cli.once('close', done)
yield server.close()
})(ilog.error)