WebSockets
Learn to establish a long-lived connection with the server via WebSockets.
We'll cover the following...
What are WebSockets?
WebSocket protocol allows for simultaneous two-way communication between the client and the server. Applications such as chatting apps and multiplayer games that rely on real-time connection with the server use WebSockets for their communication.
GetX’s internal networking library, GetConnect, allows us to establish long-lived connections with the server over WebSockets. This lesson will teach us how to manage a socket connection with the server and listen to real-time updates.
Establishing connection
We manage a WebSocket connection in GetConnect using the GetSocket class. With GetSocket, we get the methods to establish a connection, close it, and listen to the messages that pass to and from the client and server. To establish a connection, we follow three simple steps:
Create an instance of
GetConnect. We use it to create a socket connection.
Create an instance of
GetSocketusingGetConnect'ssocketmethod. Provide it the URL to connect to.
Finally, connect to the created socket using the
connectmethod. It’s an asynchronous event, so make sure to addawaitbefore the method call.
Listeners
Now that the connection is established, we can listen to the various events that take place during the life cycle of the connection. GetSocket provides us a listener method corresponding to each life cycle event. Let’s walk through all the listener methods one by one:
The
onOpenmethod: Gets triggered as soon as the connection is established. In the below example, we mark the user online when the connection opens.
The
onMessagemethod: Called every time there’s a new message passed in the connection. We pass a new message withGetSocket'ssendmethod, ...