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:

  1. Create an instance of GetConnect. We use it to create a socket connection.

Press + to interact
final GetConnect connect = GetConnect();
  1. Create an instance of GetSocket using GetConnect's socket method. Provide it the URL to connect to.

Press + to interact
final GetSocket socket = connect.socket('https://echo.websocket.org/');
  1. Finally, connect to the created socket using the connect method. It’s an asynchronous event, so make sure to add await before the method call.

Press + to interact
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:

  1. 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.

Press + to interact
socket.onOpen(() {
markUserOnline();
});
  1. The onMessage method: Called every time there’s a new message passed in the connection. We pass a new message with GetSocket's send ...