WebSocket Channel: A Comprehensive Guide
Published on by Flutter News Hub
WebSocket Channel provides cross-platform StreamChannel wrappers for WebSocket connections, enabling seamless communication between web applications and servers.
How to Use WebSocket Channel
To establish a WebSocket connection, use the WebSocketChannel class:
import 'package:web_socket_channel/web_socket_channel.dart'; final wsUrl = Uri.parse('ws://example.com'); final channel = WebSocketChannel.connect(wsUrl);
Once connected, you can listen for incoming messages and send messages to the server:
channel.stream.listen((message) { print('Received: $message'); }); channel.sink.add('Hello, server!');
Cross-Platform Implementation
WebSocket Channel includes platform-specific implementations that can be used for both WebSocket communication and server-side support:
- IOWebSocketChannel for Dart:io (server-side)
- HtmlWebSocketChannel for Dart:html (web client)
Key Features
In addition to the standard StreamChannel interface, WebSocket Channel offers several key features:
- Negotiated Protocol: The protocol getter provides information about the protocol negotiated for the socket.
- Close Information: The closeCode and closeReason getters indicate why the socket was closed.
- Customizable Closure: The WebSocketSink allows you to specify close codes and reasons when closing the connection.
- Handshake Support: The WebSocketChannel.signKey() method simplifies handshake implementation.
Protocol Status Codes
WebSocket Channel also provides constants for predefined WebSocket protocol status codes in the status library:
import 'package:web_socket_channel/status.dart' as status; // Close the connection with a going away status channel.sink.close(status.goingAway);
Conclusion
WebSocket Channel provides a comprehensive and cross-platform solution for WebSocket communication, offering both a flexible API and platform-specific implementations. Its rich feature set and support for protocol status codes make it an invaluable tool for building real-time applications.