WebSockets are used to connect with the server just like the http package. It supports two-way communication with a server without polling.
In this article we will explore the below-listed topics related to WebSockets in Flutter:
- Connecting to a WebSocket server
- Listen to messages from the server.
- Send data to the server.
- Close the WebSocket connection.
In this article as an example, we will connect to the test server provided by websocket.org.
Connect to a WebSocket Server:
The web_socket_channel package has tools that are needed to connect to a WebSocket server. The package provides a WebSocketChannel that allows users to both listen to messages from the server and push messages to the server.
In Flutter, use the following line to create a WebSocketChannel that connects to a server:
final channel = IOWebSocketChannel.connect('ws://echo.websocket.org');
Listen to messages from the server:
Now that we have established the connection to the server, we will send a message to it and get the same message as a response:
Send Data to the Server:
To send data to the server, add() messages to the sink provided by the WebSocketChannel as shown below:
Close the Connection:
To close the connection to the WebSocket use the below:
Complete Source Code: