In today’s interconnected world, the need for real-time updates is paramount for websites and IoT applications.
A way to deliver information instantly to your sites or applications is to use the Websocket protocol which provides a full-duplex communication channel between a server and a client. From 4D V20, you can create a websocket server with the 4D.WebSocketServer class. We continue in v20 R2 with the 4D.WebSocket class that allows you to create a websocket client to connect to any websocket servers.
In this blog post, we will connect to the chat server given as an example in the websocket server blog:
In this example, messages will be displayed in a listbox populated by the Form.messages collection.
manage websocket events
First, you need to create a class to manage the websocket events and instantiate it. To do so, you need to create a class with some of the following functions, depending on your needs:
- onMessage(), called each time a message arrives through this connection,
- onOpen(), called when the websocket connection is opened,
- onTerminate(), called when the websocket connection is closed,
- onError(), called when an error occurred.
In our example, we want to display the message received from the server and display the connection closing. So we create this WSConnectionHandler class:
Class constructor
Function onMessage($ws : Object; $event : Object)
Form.messages.push($event.data)
Function onTerminate($ws : Object; $event : Object)
Form.messages.push("Connection closed")
And we want to send messages written by the user to the server:
// Sends a message through the websocket client connected to the websocket server
Form.webSocket.send(Form.message)
connect to the server
To connect your application to the websocket server, you need to instantiate the 4D.WebSocket using the server url as the first parameter and your WebSocket connection handler in the second:
Form.webSocket:=4D.WebSocket.new($wssUrl; cs.WSConnectionHandler.new())
Check out this feature with the HDI and the documentation for more details!