WebSockets
Learn to establish a long-lived connection with the server via WebSockets.
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.
final GetConnect connect = GetConnect();
Create an instance of
GetSocket
usingGetConnect
'ssocket
method. Provide it the URL to connect to.
final GetSocket socket = connect.socket('https://echo.websocket.org/');
Finally, connect to the created socket using the
connect
method. It’s an asynchronous event, so make sure to addawait
before the method call.
await socket.connect();
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
onOpen
method: Gets triggered as soon as the connection is established. In the below example, we mark the user online when the connection opens.
socket.onOpen(() {markUserOnline();});
The
onMessage
method: Called every time there’s a new message passed in the connection. We pass a new message withGetSocket
'ssend
...