Integrating WebSocket with Flutter: Using WebSocket for Real-Time Applications

Integrating WebSocket with Flutter: Using WebSocket for Real-Time Applications

FlutterPulse

This article was translated specially for the channel FlutterPulseYou'll find lots of interesting things related to Flutter on this channel. Don't hesitate to subscribe!šŸš€

Developing mobile applications often requires using new technologies and methods to enhance user experience and improve application…

Developing mobile applications often requires using new technologies and methods to enhance user experience and improve application performance. One of these technologies is WebSocket. WebSocket is a protocol commonly used to meet the requirements of real-time communication.

What is WebSocket?

WebSocket is a protocol that provides full-duplex, low-latency communication. Similar to HTTP, WebSocket enables data transmission between the client and server. However, unlike HTTP, once the WebSocket connection is established, a continuous channel is created between the two parties. This allows real-time, continuous data flow between the client and server.

What is WebSocket Used For?

WebSocket is ideal for the following scenarios:

  1. Real-Time Applications: It is used in applications that require fast data transmission and reception, such as live chat, notifications, games, or financial apps.
  2. Low Latency Requirements: WebSocket is perfect for applications that require low latency. This is crucial for scenarios where the user needs immediate feedback.
  3. Continuous Connection Requirements: WebSocket is more efficient for applications that require a continuous connection for data transmission. For instance, in a chat application, messages must be delivered to the recipient immediately.

Advantages of WebSocket

  • Low Latency: WebSocket offers low latency because the connection remains open, and data is transmitted instantly.
  • Bidirectional Communication: WebSocket allows bidirectional communication between the client and server. This enables both parties to send data.
  • Efficient Data Use: Since WebSocket maintains a continuous connection, there is no need to open a new connection each time, reducing network traffic and time.

Integrating WebSocket into a Flutter Project

To use WebSocket in Flutter, you first need a WebSocket server, which can be built using technologies like Node.js. On the Flutter side, we will use the web_socket_channel package to manage the WebSocket connection.

Setting Up a WebSocket Server with Node.js

While using Flutter as the WebSocket client, we can set up the server using Node.js. Node.js is a great platform for building WebSocket servers. We will use the popular Node.js package ws to create the WebSocket server.

Step 1: Set Up the WebSocket Server with Node.js

First, ensure that Node.js and npm are installed on your system. If they are not installed, you can download and install them from Node.js's official website.

Create a new Node.js project and install the necessary packages:

mkdir websocket-server
cd websocket-server
npm init -y
npm install ws

The ws package is used to create the WebSocket server. Now, write the following code to start the server:

// server.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (ws) => {
console.log('A new client connected!');

// Listen for messages from the client
ws.on('message', (message) => {
console.log('Received message: ', message);

// Send the message back (echo functionality)
ws.send(`Message from server: ${message}`);
});

// Send a welcome message to the client
ws.send('Welcome to the WebSocket server!');
});

console.log('WebSocket server is running on port 8080...');

This code creates a WebSocket server that listens for incoming client connections. It receives messages from the client and sends them back (echo functionality). The server runs on port 8080.

Step 2: Running the Server

To start the server, run the following command in your terminal:

node server.js

Once the server is running, it will start listening on ws://localhost:8080.

Integrating WebSocket into the Flutter Project

On the Flutter side, we will use the web_socket_channel package to manage the WebSocket connection.

Step 1: Installing the WebSocket Channel Package

To add WebSocket support to your Flutter project, first, add the web_socket_channel package to your pubspec.yaml file

dependencies:
flutter:
sdk: flutter
web_socket_channel: ^lastest_version

Step 2: Configuring the WebSocket Connection

To make the WebSocket connection cleaner and more manageable, we will create a service class that handles the connection, message sending, and receiving.

import 'package:web_socket_channel/web_socket_channel.dart';

class WebSocketService {
final WebSocketChannel channel;

WebSocketService(String url) : channel = WebSocketChannel.connect(Uri.parse(url));

// Send message
void sendMessage(String message) {
if (message.isNotEmpty) {
channel.sink.add(message);
}
}

// Listen for incoming messages
Stream get messages => channel.stream;

// Close the connection
void close() {
channel.sink.close();
}
}

This service class starts the WebSocket connection, sends messages, and listens for incoming messages. The close method is used to close the connection.

Step 3: Using WebSocket Connection in Flutter UI

Now, let's create a Flutter widget that uses the WebSocket service to display messages and allow the user to send them.

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class WebSocketService {
final WebSocketChannel channel;

WebSocketService(String url) : channel = WebSocketChannel.connect(Uri.parse(url));

// Send message to WebSocket
void sendMessage(String message) {
if (message.isNotEmpty) {
channel.sink.add(message);
}
}

// Stream to listen to incoming messages
Stream get messages => channel.stream;

// Close the WebSocket connection
void close() {
channel.sink.close();
}
}

class WebSocketExample extends StatefulWidget {
@override
_WebSocketExampleState createState() => _WebSocketExampleState();
}

class _WebSocketExampleState extends State<WebSocketExample> {
late WebSocketService _webSocketService;
final TextEditingController _controller = TextEditingController();

@override
void initState() {
super.initState();
// Initialize WebSocket connection
_webSocketService = WebSocketService('ws://localhost:8080');
}

@override
void dispose() {
// Close WebSocket connection when the widget is disposed
_webSocketService.close();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("WebSocket Example")),
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: _webSocketService.messages,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
return ListView(
children: [
Text(snapshot.hasData ? '${snapshot.data}' : 'No data received yet'),
],
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Enter a message'),
),
),
IconButton(
icon: const Icon(Icons.send),
onPressed: () {
// Send message when the button is pressed
_webSocketService.sendMessage(_controller.text);
_controller.clear();
},
),
],
),
),
],
),
);
}
}

This Flutter app allows the user to type a message, send it via WebSocket, and see the server's response on the screen.

Conclusion

Integrating WebSocket with Flutter is a great solution for real-time data transmission and low-latency applications. By following the steps learned in this article, you can implement WebSocket communication in your Flutter app for instant data exchange. You can further enhance your WebSocket implementation by adding features such as session management, error handling, and security measures.

I hope my article was useful for you. You can check out my profile for more. Don't forget to follow me on Linkedin and Github šŸ˜Ž.

Report Page