Created on 12-22-2016 09:10 PM - edited 08-17-2019 07:02 AM
Setting up a Websocket Client and Server with Apache NiFi 1.1.
I wanted to test out the new WebSocket Listener in Apache NiFi 1.1, but I needed a server to serve up my HTML client. So I ran that web server with NiFi as well. So my full solution is hosted and runs through Apache NiFi.
This simple WebSockets Server and Client does the hello world of web sockets, Echo! Whatever the client sends, we send it back.
My Suggested Use Cases for WebSockets
Step 1: HandleHTTPRequest This accepts the HTTP calls from browsers
Step 2: ExecuteStreamCommand Returns HTML page (could do getfile or any number of other ways of getting the HTML as a flowfile)
Step 3: HandleHttpResponse this serves up our web page to browsers. A StandardHTTPContextMap is required to store HTTP requests and responses to share them through the stream.
Step 4: PutFile Just to keep logs of what's going on, I saw all the flow files to the local file system.
Step 5: ListenWebSocket This is the actual web socket server listener, it is what our client will talk to.
Step 6: PutWebSocket This is the reply to the web socket client.
Web Sockets Server
Web Sockets Client (Static HTML5 Page with Javascript) Hosted on NiFi
Web Socket Conversation On the Client Side
A Shell Script to Output The HTML5 Javascript WebSocket Client
➜ nifi-1.1.0.2.1.1.0-2 cat server.sh cat /Volumes/Transcend/Apps/nifi-1.1.0.2.1.1.0-2/wsclient.html ➜ nifi-1.1.0.2.1.1.0-2 cat wsclient.html <!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket is supported by your Browser!"); // Let us open a web socket var ws = new WebSocket("ws://localhost:9998/echo"); ws.send("MSG: NIFI IS AWESOME"); ws.onopen = function() { // Web Socket is connected, send data using send() ws.send("Message to send"); alert("Message is sent..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } else { // The browser doesn't support WebSocket alert("WebSocket NOT supported by your Browser!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">Run WebSocket</a> </div> </body> </html>
Construct a Visual Web Server to Server up Static HTML 5 WebSocket Client Page
Listen For Websocket
Put Message Back
Reference:
NiFi Template (This is for Apache NiFi 1.1.x)