LoginSignup
20
14

More than 3 years have passed since last update.

ngrokで複数ポート開いてWebSocketで通信する

Last updated at Posted at 2019-09-11

これまでのあらすじ

スマホのブラウザ上で加速度データを取得してWebSocketでサーバに送りたい!

センサーデータを取得するためにはhttpsじゃないと動かない…

ngrokを使ってhttpsで立てちゃお

クライアント用と通信(wss)用とで2つhttpsが必要になったぞ

ngrokで複数ポートhttpsで立てる

ngrokのサイトにログイン
ngrok - secure introspectable tunnels to localhost
Setup & Installation > 3 Connect your accountをコピペしてターミナルで実行→設定ファイルに認証情報が追記される

さらに手動で設定ファイルを書き換える
各OSにおける設定ファイルの場所はこちら
Default configuration file location _ ngrok – documentation


authtoken: xxxxxxx

tunnels:
  client:
    addr: 8000
    proto: http
  wss:
    addr: 3000
    proto: http

ターミナルから名前を指定してngrokを起動
この場合はclientとwss

ngrok start client wss

8000番ポートと3000番ポートが同時にhttpsで利用できる!やったー

WebSocketでのopen

var sock = new WebSocket('wss://xxxxx.ngrok.io'); // 3000番ポートを利用

// 接続
sock.addEventListener('open', function (e) {
    console.log('Socket 接続成功');
});

クライアントは8000番ポートで立ち上げればOK

参考リンク

20
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
14