How websocket works entire flow ?
Answer
Overview
WebSocket is a communication protocol that provides a full-duplex, persistent connection between client and server over a single TCP connection — enabling real-time, bidirectional data transfer.
WebSocket vs HTTP
| Feature | HTTP | WebSocket |
|---|---|---|
| Connection | Request-response (open/close each time) | Persistent (stays open) |
| Direction | Client → Server only | ↔ Bidirectional |
| Overhead | High (headers each request) | Low (after handshake) |
| Real-time | ❌ Polling needed | ✅ Instant push |
| Use case | Standard API calls | Chat, live prices, games |
Entire WebSocket Flow
text1. HTTP HANDSHAKE (Upgrade) Client → Server: GET /chat HTTP/1.1 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Server → Client: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: ... 2. CONNECTION ESTABLISHED TCP connection stays open — no more HTTP headers needed 3. BIDIRECTIONAL MESSAGING Client → Server: {"type": "message", "text": "Hello!"} Server → Client: {"type": "message", "text": "Hi there!", "from": "Alice"} Server → Client: {"type": "typing", "user": "Bob"} ← Server pushes without request 4. CLOSE Client → Server: Close frame (code 1000 = Normal closure) Server → Client: Close frame (confirms) TCP connection closed
Flutter WebSocket Implementation
dartimport 'dart:io'; import 'dart:convert'; class WebSocketService { WebSocket? _socket; final StreamController<String> _messageController = StreamController.broadcast(); Stream<String> get messages => _messageController.stream; Future<void> connect(String url) async { _socket = await WebSocket.connect(url); print('WebSocket connected'); _socket!.listen( (data) { _messageController.add(data.toString()); }, onError: (error) { print('WebSocket error: $error'); _reconnect(url); }, onDone: () { print('WebSocket closed'); }, ); } void send(Map<String, dynamic> data) { if (_socket?.readyState == WebSocket.open) { _socket!.add(jsonEncode(data)); } } void _reconnect(String url) async { await Future.delayed(Duration(seconds: 3)); await connect(url); } void disconnect() { _socket?.close(); _messageController.close(); } }
Using web_socket_channel (Recommended Package)
dartimport 'package:web_socket_channel/web_socket_channel.dart'; class ChatScreen extends StatefulWidget { _ChatScreenState createState() => _ChatScreenState(); } class _ChatScreenState extends State<ChatScreen> { late WebSocketChannel channel; final _controller = TextEditingController(); List<String> messages = []; void initState() { super.initState(); channel = WebSocketChannel.connect( Uri.parse('wss://echo.websocket.events'), ); channel.stream.listen((message) { setState(() => messages.add(message)); }); } void _sendMessage() { if (_controller.text.isNotEmpty) { channel.sink.add(jsonEncode({ 'type': 'message', 'text': _controller.text, })); _controller.clear(); } } void dispose() { channel.sink.close(); super.dispose(); } Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Expanded( child: ListView.builder( itemCount: messages.length, itemBuilder: (context, i) => ListTile(title: Text(messages[i])), ), ), Row( children: [ Expanded(child: TextField(controller: _controller)), IconButton(icon: Icon(Icons.send), onPressed: _sendMessage), ], ), ], ), ); } }
WebSocket Use Cases
| Use Case | Why WebSocket? |
|---|---|
| Live chat | Instant bidirectional messaging |
| Stock/crypto prices | Server pushes updates |
| Multiplayer games | Low-latency real-time sync |
| Collaborative editing | Real-time cursor + content sync |
| Live notifications | Push without polling |
| IoT dashboard | Stream device data |
Key Advantage: WebSocket eliminates polling — instead of asking "any new data?" every second (wasteful), the server pushes data the moment it's available (efficient).