websockets-cli: a friendly companion to your web project
Tags: webdev, python, websockets
Published: 2022-07-18 06:55:55

In this article, I will present my last open source project I have been working on for the last few months, [websockets-cli](https://pyws.readthedocs.io/en/latest/). It is a Command Line Interface (CLI) to interact with a [websocket](https://en.wikipedia.org/wiki/WebSocket) server.

## Why?

There are two main reasons for this project:

- Each time I work on a web project involving websockets, I found myself wanting a simple CLI tool to test what I have
  coded. I always ended up writing a script to solve this issue because I could not find an appropriate library.
- It is a fun project to do 🙃

Of course, there are graphical solutions like [Postman](https://www.postman.com/) to help you with websockets, but I'm sure I'm not the only one who prefer to work with the terminal for such testing.

## Installation

To install it, you will need **python3.7** or newer and _pip_ installed. After that, you can type:

```shell
$ pip install websockets-cli
```

You can also use another package manager like [poetry](https://python-poetry.org/docs/). I have
a [tutorial](https://medium.com/analytics-vidhya/poetry-finally-an-all-in-one-tool-to-manage-python-packages-3c4d2538e828) on it if you don't know this tool.

```shell
$ poetry add -D websockets-cli
```

If you want some kind of global installation, you can use the [pipx](https://pypa.github.io/pipx/) library.

```shell
$ pipx install websockets-cli
```

## Settings

There are many settings you can configure for your needs. There are all defined in this [section](https://pyws.readthedocs.io/en/latest/settings/) of the official documentation. You can configure them either using the:

- [pyproject.toml](https://peps.python.org/pep-0621/) file
- environment variables
- a custom env file named `.ws.env` in your current working directory or home directory.

Note:
 - the pyproject.toml file has precedence over environment variables.

## Usage

The CLI is straightforward to use. To know all available commands, just type `ws` in the terminal:

```shell
$ ws
Usage: ws [OPTIONS] COMMAND [ARGS]...

  A convenient websocket cli.

  Example usage:

  # listens incoming messages from endpoint ws://localhost:8000/path
  $ ws listen ws://localhost:8000/path

  # sends text "hello world" in a text frame
  $ ws text wss://ws.postman-echo.com/raw "hello world"

  # sends the content from json file "hello.json" in a binary frame
  $ ws byte wss://ws.postman-echo.com/raw file@hello.json

Options:
  --version   Show the version and exit.
  -h, --help  Show this message and exit.

Commands:
  byte                Sends binary message to URL endpoint.
  echo-server         Runs an echo websocket server.
  install-completion  Install completion script for bash, zsh and fish...
  listen              Listens messages on a given URL.
  ping                Pings a websocket server located at URL.
  pong                Sends a pong to websocket server located at URL.
  session             Opens an interactive session to communicate with...
  tail                An emulator of the tail unix command that output...
  text                Sends text message on URL endpoint.
```

### Install-completion

The first command to use is `install-completion` which will add completion support for commands and options. It will work for `bash`, `fish` and `zsh`. Windows support (Powershell) is planned.

```shell
$ ws install-completion
# when the command succeeded, you should see the following message
Successfully installed completion script!
```

### Echo-server

If you want to self-host an echo websocket server like Postman [does](https://blog.postman.com/introducing-postman-websocket-echo-service/), you can run the `echo-server` command. Here is an example:

```shell
$ ws echo-server -H ::1 -p 8000
Running server on ::1:8000 💫
# To stop the server, you can just tap Ctrl+C
^CProgram was interrupted by Ctrl+C, good bye! 👋
```

### Listen

Often, you will want to see incoming messages from a websocket endpoint. It is really easy with websockets-cli:

```shell
# assuming you have an endpoint localhost:8000 sending messages
$ ws listen :8000
# you will have an output like the following
──────────────────── TEXT message on 2022-05-25 07:10:07 ────────────────────────────────────
{"hello": "world"}
──────────────────── BINARY message on 2022-05-25 07:10:07 ──────────────────────────────────────
b'{"hello": "world"}'
```

### Session

Probably the command you will use the most. It allows a complete interaction with a websocket server. You can send `ping`, `pong`, `close`, `text` and `binary` frames.

```shell
$ ws session wss://ws.postman-echo.com/raw
Welcome to the interactive websocket session! 🌟
For more information about commands, type the help command.
When you see <> around a word, it means this argument is optional.
To know more about a particular command type help <command>.
To close the session, you can type Ctrl+D or the quit command.

> help
The session program lets you interact with a websocket endpoint with the
following commands:

• ping <message>: Sends a ping with an optional message.
• pong <message>: Sends a pong with an optional message.
• text message: Sends text message.
• byte message: Sends byte message.
• close <code> <reason>: Closes the websocket connection with an optional code
and message.
• quit: equivalent to close 1000.

> help close
Closes the session given a code and an optional reason.

Example usage:

If no code is given, 1000 is considered as default meaning a normal closure.
Thus, it is equivalent to the quit command.

┌────────────────────────────────────────────────────────────────────────────┐
│ > close                                                                    │
└────────────────────────────────────────────────────────────────────────────┘

Closes the connection with a code 1001 and no message.

┌────────────────────────────────────────────────────────────────────────────┐
│ > close 1001                                                               │
└────────────────────────────────────────────────────────────────────────────┘

Closes the connection with a code 1003 and a message "received unknown data".

The message length must not be greater than 123 bytes.

┌────────────────────────────────────────────────────────────────────────────┐
│ > close 1003 'received unknown data'                                       │
└────────────────────────────────────────────────────────────────────────────┘

To know more about close codes, please refer to the RFC.
> quit
Bye! 👋
```

Thanks to [prompt-toolkit](https://python-prompt-toolkit.readthedocs.io/en/master/), the session command has features like:

- Syntax highlighting
- Auto-completion of subcommands
- Ability to read history of the previous commands typed during the current session
- Autosuggestion of commands based on your history within the current session.

I will stop here for the presentation, if you want to know more about the project, you can read the official [documentation](https://pyws.readthedocs.io/en/latest/).
I hope you will find it interesting to use if you play a lot with websockets. 🙂

---

If you like my article and want to continue learning with me, don’t hesitate to follow me here and subscribe to my [newsletter](https://www.getrevue.co/profile/le_woudar) 😉