VOOZH about

URL: https://www.geeksforgeeks.org/flutter/flutter-websockets/

⇱ Flutter - WebSockets - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flutter - WebSockets

Last Updated : 15 Jul, 2025

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.

1. 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');

2. 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:

3. Send Data to the Server

To send data to the server, add() messages to the sink provided by the WebSocketChannel, as shown below:

channel.sink.add('Hello Geeks!');

4. Close the Connection

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:


Comment
Article Tags:

Explore