Building Real-Time Flutter Apps with CC Web Socket

Ferhat Erdem
4 min readJun 19, 2024

--

Welcome to the world of real-time Flutter applications! Today, I’m excited to introduce you to CC Web Socket, a robust and flexible WebSocket client designed specifically for Flutter applications. Whether you’re building a chat app, a live trading platform, or any real-time application, CC Web Socket has got you covered.

Why WebSockets?

Before diving into the details of CC Web Socket, let’s talk about why WebSockets are essential. Traditional HTTP requests are great for many tasks, but they fall short when it comes to real-time communication. WebSockets provide a persistent connection between the client and server, allowing for instantaneous two-way data transfer. This is perfect for applications where timely updates are crucial.

Introducing CC Web Socket

CC Web Socket makes it incredibly easy to manage WebSocket connections in Flutter. With simple setup options, detailed logging, and modular architecture, it is designed to meet the needs of both beginners and experienced developers.

Key Features

  • Easy Initialization: Start with WebSockets in no time with straightforward configuration.
  • Timeout and Ping Settings: Customize your connection settings to ensure stability and responsiveness.
  • Automatic Reconnection: Never worry about dropped connections; CC Web Socket handles reconnections for you.
  • Detailed Logging: Keep track of your connection status, requests, and responses with built-in logging.
  • Modular Structure: Extend and customize functionality with ease using modules.

Getting Started

Let’s walk through how to get started with CC Web Socket in your Flutter project.

Installation

First, add the package to your pubspec.yaml file:

dependencies: cc_web_socket: ^1.0.0

Then, run flutter pub get to install the package.

Initialization

Initialize CC Web Socket with your desired settings. Here’s a quick example:

import 'package:cc_web_socket/cc_web_socket.dart';

void main() {
CCWebSocket.init(
socketOptions: CCSocketOptions(
uri: Uri(
scheme: "wss",
host: "echo.websocket.org",
port: 443,
path: ".ws",
),
connectTimeout: const Duration(seconds: 5),
pingInterval: const Duration(seconds: 120),
requestTypeName: "request_type",
autoConnect: true,
),
loggingOptions: CCSocketLogging(
logEnabled: true,
onConnection: (prompt) => print("Connected: $prompt"),
onReconnection: (prompt) => print("Reconnecting: $prompt"),
onClosed: (prompt) => print("Connection closed: $prompt"),
onRequest: (prompt) => print("Request: $prompt"),
onResponse: (prompt) => print("Response: $prompt"),
onError: (prompt) => print("Error: $prompt"),
),
modules: [
Example(),
],
);
}

In this example, we’re connecting to a WebSocket echo service. You can customize the uri, timeouts, and logging options as needed.

NOTE: The requestTypeName parameter is an identifier in the JSON content that matches the correct module for the returned data.

Connecting

To establish the connection, simply call:

CCWebSocket.connect();

Using Modules

Modules allow you to structure your WebSocket communication efficiently. Here’s how you can send a request through a module:

CCWebSocket.getModule<Example>().request(
body: {
"request_type": "Unknown",
},
);

Creating Custom Modules

Creating your own module is straightforward. Here’s an example of how to define a custom module:

class Example extends RequestModule {
@override
void request({required Map<String, dynamic> body}) {
super.request(body: body);
}

@override
void response(dynamic response) {
print("Response received: $response");
}
}

You can handle both requests and responses in your module, providing a clean separation of concerns.

A Real-World Example

Let’s put it all together in a real-world example. Suppose you’re building a live chat application. Here’s how you might set it up with CC Web Socket.

Initializing the WebSocket

void main() {
CCWebSocket.init(
socketOptions: CCSocketOptions(
uri: Uri(
scheme: "wss",
host: "yourchatserver.com",
port: 443,
path: "/chat",
),
connectTimeout: const Duration(seconds: 5),
pingInterval: const Duration(seconds: 60),
requestTypeName: "message_type",
autoConnect: true,
),
loggingOptions: CCSocketLogging(
logEnabled: true,
onConnection: (prompt) => print("Connected to chat server."),
onReconnection: (prompt) => print("Reconnecting to chat server..."),
onClosed: (prompt) => print("Chat server connection closed."),
onRequest: (prompt) => print("Message sent: $prompt"),
onResponse: (prompt) => print("Message received: $prompt"),
onError: (prompt) => print("Chat server error: $prompt"),
),
modules: [
ChatModule(),
],
);

CCWebSocket.connect();
}

Defining the Chat Module

class ChatModule extends RequestModule {
@override
void request({required Map<String, dynamic> body}) {
super.request(body: body);
}

@override
void response(dynamic response) {
print("New chat message: $response");
}
}

Sending a Message

void sendMessage(String message) {
CCWebSocket.getModule<ChatModule>().request(
body: {
"message_type": "chat",
"content": message,
},
);
}

With these steps, you’ve created a basic live chat application using CC Web Socket. This modular approach keeps your code clean and manageable, making it easy to extend with new features.

Conclusion

CC Web Socket is a powerful tool for any Flutter developer looking to add real-time capabilities to their applications. Its ease of use, robust features, and modular design make it a go-to choice for WebSocket management in Flutter.

I hope this guide helps you get started with CC Web Socket and inspires you to build amazing real-time applications. If you have any questions or feedback, feel free to reach out or contribute to the project. Happy coding!

--

--

Ferhat Erdem

I have been actively working in the software industry for approximately seven years.