LoginSignup
22
23

More than 5 years have passed since last update.

CLIのWebsocketクライアントを作ってみた

Posted at

Websocketを使ったサーバを作ったときに、動作確認をJavaScriptで書くのが面倒なのでターミナル上でやりたいと思いました。

wscatwsshというツールが既にありますが、npmpythonをインストールしないとダメなのと、自分で作ってみたかったのでGoで実装しました。

https://github.com/morikuni/weso

つくったもの

wesoというコマンドを作りました。
telnet的に文字列を送受信できます。

https://github.com/morikuni/weso/releasesからバイナリをダウンロードして実行できます(動作未確認)。

使い方

wesoにURLを渡すことで接続されます。

$ weso ws://echo.websocket.org
> hello world
<< hello world
> how are you?
<< how are you?

ここでは、ws://echo.websocket.orgという送ったメッセージをそのまま返してくるサーバに接続しています。
>と表示されている行が送信した文字列で、<<と表示されている行がサーバから受信した文字列です。

wesoの特徴はテンプレートを使って文字列を送信できることです。
例えばJSON形式でデータを送りたいときに毎回{"name":"Gopher"}のように書くのは大変ですが、テンプレートを使うことで関数呼び出しのようにJSONを作成できます。

$ cat template.txt
{{define "Name"}}{"name": "{{._1}}"}{{end}}
{{define "JSON"}}{"{{._1}}": "{{._2}}"}{{end}}

$ weso -template template.txt ws://echo.websocket.org
> .Name Gopher
<< {"name": "Gopher"}
> .JSON message Hello
<< {"message": "Hello"}

テンプレートファイルはGoのtemplateライブラリの形式です。
{{define "XXX"}}から{{end}}までが1つのテンプレートです。
テンプレートへの引数は._1,._2...._Nで取得することができます。

Websocketサーバの簡単な動作確認には便利だと思うのでよかったら使ってみてください。

22
23
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
22
23