Education
Software Development Executive - I
Software Development Executive - II
Last updated onSep 15, 2023
Last updated onAug 3, 2023
In the realm of 'real-time web', Flutter WebSockets have made their stellar mark. Rightfully so, owing to their dependable WebSocket-based solution, they are notably the new favourite in the coding community. It's here that the 'real-time web existed' makes sense!
WebSockets allow real-time data exchange between a client and server over a perplexing but fascinating technology - WebSocket. So, imagine the protocol as an agreement between the WebSocket client and the WebSocket server. It declares, "Hey! Let's keep the connection open until we decide to part ways."
When I embarked on my journey to deep-dive into WebSockets, I realized that the WebSocket sits comfortably atop the Internet Protocol (IP) and shares a strong bond with its cousin- The Hypertext Transfer Protocol (HTTP). But the WebSocket breaks away from their family tradition. Unlike HTTP, where client-server communication is request-based, the WebSocket protocol happily entertains two-way communication, rapid data exchange, and immediate message update.
HTTP has been a linchpin of server-client communication. It facilitated data transfer over the web in a streamlined manner. A client sends a request to a server, the server processes that request returns the corresponding response, and finally, the connection closes.
1 HttpClient client = new HttpClient(); 2 client.getUrl(Uri.parse("http://yourHttpServer/path")) 3 .then((HttpClientRequest request) { 4 return request.close(); 5 }) 6 .then((HttpClientResponse response) { 7 // Process the HTTP Response here. 8 }); 9
But with HTTP, communication is solely initiated by the client, putting the server's role in question when pushing data to the client in real-time.
With WebSockets, the paradigm shifts to a two-way, full-duplex mode of communication. This means both client and server can send data to each other anytime until the connection is open.
1 WebSocket ws = await WebSocket.connect('ws://yourWebsocketServer/path'); 2 ws.add('Hello from client!'); // Client sends a message 3 ws.listen((event) { // Client receives a message 4 print('Received: $event'); 5 }); 6
One of the best attributes of WebSockets is its ability to handle concurrent client connections, wherein the same message can be broadcast to multiple clients.
While HTTP and WebSockets fundamentally serve the same purpose (communication between a client and a server), the way they achieve it is strikingly different.
HTTP is a protocol renowned for its simplicity and reliability, widely used to get or send data to a server. However, WebSockets go a notch higher. Its persistent connections and features like sending, listening, and pushing messages make it a seamless option for real-time web applications.
Choosing between HTTP and WebSockets depends on what you need in your Flutter application. For rudimentary data transfer or API calls, HTTP is ideal. But, if you're venturing into chat applications, real-time data sync, or similar implementations, WebSockets release their true prowess.
In simple words, consider HTTP a letter mailed to you: it has valuable information but is not delivered in real-time. On the other hand, WebSockets are analogous to a phone call: information is exchanged in real-time with both parties actively involved.
Before you dive into the realm of Websockets, the first thing that you need to do is set up a new Flutter project. You can use the Flutter CLI tool to generate a new project template:
1 flutter create ws_flutter_example 2
Once the project creation process completes, navigate into your new project by using the cd command:
1 cd ws_flutter_example 2
This will leave you with a simple, runnable Flutter app.
With your packages now set up, you need to import them into your Dart files.
In your Dart file (Let's assume 'main.dart'), add:
1 import 'package:flutter/material.dart'; 2 import 'package:web_socket_channel/web_socket_channel.dart'; 3
Now you're all set to move forth and start coding with the power of WebSockets in your Flutter application. The added packages provide you with the tools in your arsenal to effectively and efficiently work with Websockets.
Installing the WebSocket package is one of the most vital steps toward establishing communication between a client and a server. This package becomes the linchpin holding together the 'connection', which enables the client, i.e., your Flutter application, to listen, send data to the server, and push messages.
Incorporating the WebSocket package into your Flutter app requires a dedicated entry in the 'pubspec.yaml' file. This is the go-to file for adding all dependencies for your Flutter project.
1 dependencies: 2 web_socket_channel: ^2.1.0 3
After adding this to your 'pubspec.yaml' file, don't forget to install this package by running this terminal command.
1 flutter pub get 2
Voila! Your WebSocket package is ready to be used.
After incorporation, employing the WebSocket package in your Flutter application begins with importing the 'WebSocketChannel' from the package.
1 import 'package:web_socket_channel/web_socket_channel.dart';
The establishment requires the creation of a WebSocket channel. For this, you must import the WebSocket package and use the WebSocketChannel.connect() constructor.
1 import 'package:web_socket_channel/io.dart'; 2 3 final channel = IOWebSocketChannel.connect( 4 Uri.parse('ws://yourWebSocketServer/path'), 5 ); 6
With your invocation of the IOWebSocketChannel.connect(), you create a connection to the URL provided. Here, IOWebSocketChannel provides you with an easy-to-use interface to the WebSocket.
Let's understand how to open a WebSocket communication between a server and a client.
In Flutter, when you want to connect to a WebSocket and send data to a server, you use the WebSocketChannel's sink.add() method. The 'sink' property, an integral part of the WebSocket channel, functions as a repository where you can place data. This data is then transported to the server.
1 channel.sink.add('Hello from client'); 2
Data sent by the server over an established WebSocket connection can be received by listening to the stream property of the WebSocketChannel. The data received from the server can be a broadcast message sent to multiple clients or a specific message sent to a single client.
1 channel.stream.listen((message) { 2 print('Received: $message'); 3 }); 4
Closing a WebSocket connection when it's no longer needed is an essential aspect of managing resources and ensuring the smooth running of your Flutter application. Closing a connection is straightforward with the simplicity of the WebSocket API.
1 channel.sink.close(); 2
As we conclude, let's remember that WebSockets is not a replacement for HTTP; It's an addition to enable use cases that were previously complex to implement. Embrace the beauty of the WebSocket, experiment and build real-time applications, face challenges, debug errors, and keep delving into this mesmerizing domain of real-time web communication.
Whether sending data to the server, parsing incoming messages, listening to the stream of letters from the server, or handling hundreds and thousands of simultaneous client connections, WebSockets have covered you on all fronts.
In this endless journey of discovery and exploration of new tools that facilitate more straightforward and efficient coding, I want you to meet an IDE plugin called WiseGPT, developed by DhiWise, that significantly transforms the coding process.
WiseGPT is a plugin that promotes speedy and error-free coding by generating accurate code for APIs in your Flutter project. It understands your coding style and functions without specific prompts.
It's well worth exploring WiseGPT and discovering how it can influence and shape your coding journey with its limitless capabilities. Get started with WiseGPT, and experience coding like never before
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.