Create WebSocket Route
WebSocket enables the full-duplex communication between the client and server with low overheads and latency.
This guide will teach you how to create WebSocket route on API7 Cloud.
Prepare the Environment
Deploy Apache APISIX
Please refer to How to Deploy Apache APISIX to learn how to deploy Apache APISIX and connect it to API7 Cloud. In this guide, we'll deploy an Apache APISIX instance on Docker.
Deploy the WebSocket Echo Server
We'll use the image jmalloc/echo-server to deploy a WebSocket server on Docker. This server will echo the message sent from the client.
docker run --name websocket -d jmalloc/echo-server --nework <Apache APISIX Container Network ID>
We deploy this container with the same network as the Apache APISIX container. You can run the command below to get the network id of the Apache APISIX container.
docker inspect <Apache APISIX Container Name/ID> -f '{{ .NetworkSettings.Networks.bridge.NetworkID }}'
Create Service and Route
We'll create a Service with the following details in this guide.
- The Service name is
websocket
. - The path prefix is
/v1
. - The HTTP Host is
websocket.local
. - Set the upstream URL to the IP address of WebSocket server container (in our case, it's
http://172.17.0.5:8080
). Please use the below command to get the correct IP address in your run.
You can run the command below to fetch the container address of the WebSocket server.
docker inspect websocket -f '{{ .NetworkSettings.Networks.bridge.IPAddress }}'
Besides, we'll create a route inside the websocket
Service.
- The route name is
mirror
. - The path is
/ws
(exact match). - Accepted HTTP method is
GET
. - Click on the Enable WebSocket checkbox.
The Enable WebSocket checkbox controls if your Apache APISIX should respect the WebSocket upgrade
request. Once you click on it, API7 Cloud will add the label WebSocket
for this route. This label marks
the route type, and without actual impacts for this route, it's your liberty to decide to save or remove this label.
If you don't know how to configure a service and route, please refer to the Getting Started guides first
Test the WebSocket Route
Let's use the wscat utility to test whether the WebSocket route is working.
wscat --connect ws://127.0.0.1:9080/v1/ws -H 'Host: websocket.local'
You'll enter an interactive console where you can send messages.
Connected (press CTRL+C to quit)
< Request served by eed6f64d8053
> Hello, API7 Cloud!
< Hello, API7 Cloud!
> API7 Cloud is a centralized platform to connect your APIs in any cloud.
< API7 Cloud is a centralized platform to connect your APIs in any cloud.
Messages led with <
are sent by the WebSocket server.