![]() |
VOOZH | about |
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:
In this article, as an example, we will connect to the test server provided by websocket.org.
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');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:
To send data to the server, add() messages to the sink provided by the WebSocketChannel, as shown below:
channel.sink.add('Hello Geeks!');To close the connection to the WebSocket, use the below:
channel.sink.close();Complete Source Code (main.dart)
To know more about HTTP pacage, TextButton, FutureBuilder in flutter refer this article: Implementing Rest API in Flutter, Flutter – TextButton Widget, Flutter – FutureBuilder Widget.
Output: