WebSocket is a communications protocol that provides full-duplex communication channels to web servers and clients over a single TCP connection. The protocol was standardized by the World Wide Web Consortium (W3C) and has been in common use by web developers for more than a decade.
Red Hat 3scale API Management is a hosted environment for web applications. In this quick tip, you will see how to use 3scale to set up WebSocket communication easily. Figure 1 shows how 3scale mediates between the web client and the WebSocket interface on the server.
This tip takes you through the following steps:
- Setting up the WebSocket server.
- Configuring 3scale API Management.
- Using a WebSocket client to test the WebSocket endpoint.
Step 1: Set up the WebSocket server
You can use any of your favorite frameworks to start the WebSocket server. For this article, we use Node.js. (Installing Node.js is out of the scope of this tip.)
We'll also use a simple JavaScript program that sets up a WebSocket server, accepts a request, and sends a reply. You can save it as index.js
:
// Minimal amount of secure websocket server
var fs = require('fs');
// read ssl certificate
var privateKey = fs.readFileSync('ssl-cert/key.pem', 'utf8');
var certificate = fs.readFileSync('ssl-cert/certificate.pem', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var https = require('https');
//pass in your credentials to create an https server
var httpsServer = https.createServer(credentials);
httpsServer.listen(8443,"0.0.0.0");
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
server: httpsServer
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('reply from server : ' + message)
});
ws.send('something');
});
You can use Node.js to start the script:
$ node index.js
Step 2: Configure 3scale API Management
Follow the 3scale documentation to add a back end and create the necessary metrics, products, and application plan to expose an endpoint. Provide the WebSocket server URL as the Private Base URL, as shown in Figure 2.
Add your WebSockets policy to the policy chain, as shown in Figure 3. No configuration is needed inside the policy.
Promote the endpoint to the staging API Gateway for testing. Figure 4 shows how the endpoint and mapping rules appear in the console.
Step 3: Use a WebSocket client to test the WebSocket endpoint
A convenient client we use for testing in this example is the Chrome browser's Web Socket Client extension. Enter the staging API Gateway URL and append the WebSocket public path to connect, as shown in Figure 5.
Conclusion
3scale API Management offers policies to support communication between your front end and back end. See these resources for further information:
Last updated: September 19, 2023