UNPKG

2.42 kBPlain TextView Raw
1/**
2 * Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
3 *
4 * @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
5 * Wechaty Contributors <https://github.com/wechaty>.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 */
20import {
21 createServer,
22 Socket,
23} from 'net'
24
25import {
26 log,
27} from './config'
28
29export class Doctor {
30
31 constructor () {
32 log.verbose('Doctor', 'constructor()')
33 }
34
35 public chromedriverVersion (): string {
36 const spawn = require('child_process').spawnSync
37 let version: string
38 try {
39 const cmd = spawn('chromedriver', ['--version'])
40 version = cmd.error || cmd.stdout.toString() || cmd.stderr.toString()
41 } catch (e) {
42 version = e.message
43 }
44 return version
45 }
46
47 /**
48 * https://gist.github.com/tedmiston/5935757
49 */
50 public testTcp (): Promise<boolean> {
51 log.verbose('Doctor', 'testTcp()')
52
53 return new Promise<boolean>((resolve, reject) => {
54 /**
55 * Server
56 */
57 const server = createServer(socket => socket.pipe(socket))
58 /**
59 * Promise Reject
60 */
61 server.on('error', reject)
62 server.on('close', () => log.silly('Doctor', 'testTcp() server closed'))
63
64 server.listen(8788, 'localhost', () => {
65 /**
66 * Client
67 */
68 const client = new Socket()
69 client.connect(8788, 'localhost', () => {
70 log.silly('Doctor', 'testTcp() client connected')
71 client.write('ding')
72 })
73
74 client.on('data', () => {
75 /**
76 * Promise Resolve
77 */
78 resolve(true)
79
80 client.destroy() // kill client after server's response
81 })
82 /**
83 * Promise Reject
84 */
85 client.on('error', reject)
86
87 client.on('close', () => server.close())
88 })
89 })
90 }
91
92}
93
\No newline at end of file