doctor.ts 2.3 KB
Newer Older
1
/**
2
 *   Wechaty - https://github.com/wechaty/wechaty
3
 *
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
4
 *   @copyright 2016-2018 Huan LI <zixia@zixia.net>
5
 *
6 7 8 9 10 11 12 13 14 15 16
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
17 18
 *
 */
Huan (李卓桓)'s avatar
Huan (李卓桓) 已提交
19 20 21 22
import {
  createServer,
  Socket,
}                   from 'net'
23 24 25 26 27 28

import {
  log,
}                   from './config'

export class Doctor {
29

30
  constructor () {
31 32 33
    log.verbose('Doctor', 'constructor()')
  }

34
  public chromedriverVersion (): string {
35
    const spawn = require('child_process').spawnSync
36 37
    let version: string
    try {
38
      const cmd = spawn('chromedriver', [ '--version' ])
39 40 41 42 43 44 45
      version = cmd.error || cmd.stdout.toString() || cmd.stderr.toString()
    } catch (e) {
      version = e.message
    }
    return version
  }

46 47 48
  /**
   * https://gist.github.com/tedmiston/5935757
   */
49
  public testTcp (): Promise<boolean> {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    log.verbose('Doctor', 'testTcp()')

    return new Promise<boolean>(async (resolve, reject) => {
      /**
       * Server
       */
      const server = createServer(socket => socket.pipe(socket))
      /**
       * Promise Reject
       */
      server.on('error', reject)
      server.on('close', () => log.silly('Doctor', 'testTcp() server closed'))

      server.listen(8788, 'localhost', () => {
        /**
         * Client
         */
        const client = new Socket()
        client.connect(8788, 'localhost', () => {
          log.silly('Doctor', 'testTcp() client connected')
          client.write('ding')
        })

73
        client.on('data', () => {
74 75 76 77 78 79 80 81 82 83 84 85
          /**
           * Promise Resolve
           */
          resolve(true)

          client.destroy() // kill client after server's response
        })
        /**
         * Promise Reject
         */
        client.on('error', reject)

86
        client.on('close', () => server.close())
87 88 89
      })
    })
  }
90

91
}