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:
- Getting Started with Cross-Platform Mobile Application using Flutter
- Difference between React Native and Flutter
- Difference Between Rows and Columns vs Container in Flutter
- Multi Page Applications in Flutter
- Routes and Navigator in Flutter
- Container class in Flutter
- Difference Between Stateless and Stateful Widget in Flutter
- Rive animations in Flutter
- ProgressIndicator in Flutter
- Flutter - Stateful vs Stateless Widgets
- Wrap Widget in Flutter
- Listview.builder in Flutter
- Splash Screen in Flutter
- How to Add images in Flutter App?
- Raised Button widget in Flutter
- Fluttertoast in Flutter
- Flutter - Architecture Application
- Designing a Form Submission Page in Flutter
- Creating a Simple Application in Flutter
- Customizing Fonts in Flutter
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.