1
+ import http from 'http'
2
+ import { host , port , serverUrl , iters } from '../config'
3
+ import PerformanceTimer from '../PerformanceTimer'
4
+
5
+ const reqOptions = {
6
+ hostname : host ,
7
+ port : port ,
8
+ path : '/hello' ,
9
+ method : 'POST' ,
10
+ headers : { 'Content-Type' : 'application/json' }
11
+ }
12
+
13
+ const postData = JSON . stringify ( { name : 'Fran' } )
14
+
15
+ // Would be great to have Promise.defer :_(
16
+ class Deferred {
17
+ resolve = null
18
+ reject = null
19
+ constructor ( ) {
20
+ this . promise = new Promise ( ( resolve , reject ) => {
21
+ this . resolve = resolve
22
+ this . reject = reject
23
+ } )
24
+ }
25
+ }
26
+
27
+ async function request ( reqOptions ) {
28
+ const deferred = new Deferred ( ) // Promise.defer() => not supported
29
+
30
+ const req = http . request ( reqOptions , resp => {
31
+ let strData = ''
32
+
33
+ // A chunk of data has been recieved.
34
+ resp . on ( 'data' , chunk => strData += chunk )
35
+
36
+ // The whole response has been received. Print out the result.
37
+ resp . on ( 'end' , ( ) => {
38
+ const data = JSON . parse ( strData )
39
+ deferred . resolve ( data )
40
+ } )
41
+
42
+ } )
43
+
44
+ req . on ( 'error' , err => {
45
+ console . log ( err )
46
+ deferred . reject ( err )
47
+ } )
48
+
49
+ req . write ( postData )
50
+ req . end ( )
51
+
52
+ return deferred . promise
53
+ }
54
+
55
+ export async function runTest ( ) {
56
+ console . log ( `Http client connecting to http://${ host } :${ port } ` )
57
+
58
+ const timer = new PerformanceTimer ( )
59
+
60
+ console . log ( `Running test with ${ iters } iterations...` )
61
+
62
+ timer . start ( )
63
+
64
+ let i = iters
65
+ await ( async function asyncLoop ( ) {
66
+ const data = await request ( serverUrl , reqOptions )
67
+ const { hello } = data
68
+ console . log ( hello )
69
+
70
+ if ( -- i === 0 ) return
71
+ await asyncLoop ( )
72
+ } ) ( )
73
+
74
+ timer . end ( )
75
+ }
76
+
77
+ if ( require . main === module ) {
78
+ runTest ( )
79
+ }
0 commit comments