Dart용 가벼운 WebSocket 클라이언트로, 클라이언트와 서버 간 실시간 통신을 가능하게 합니다. 네트워크 장애 시에도 안정적인 연결을 보장하기 위해 내장된 자동 재연결 기능을 갖추고 있습니다. 단순성과 신뢰성을 고려하여 설계되었으며, Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원합니다. 채팅 앱, 실시간 업데이트 또는 협업 도구와 같이 지속적이고 양방향 데이터 스트림이 필요한 애플리케이션에 적합합니다.
사용 사례
실시간 채팅 애플리케이션
실시간 데이터 스트리밍
협업 편집 도구
사물인터넷 장치 통신
알림 시스템
주요 기능
자동 재연결
크로스 플랫폼 지원
간단한 API
내장형 오류 처리
경량이고 효율적
적합한 대상
실시간 기능을 구축하는 개발자
지속적인 연결이 필요한 앱
다중 플랫폼 프로젝트
연결 안정성을 우선시하는 팀
고려 사항
호환되는 WebSocket 서버가 필요합니다
특정 사용 사례에 맞는 사용자 정의 재시도 로직이 필요할 수 있습니다
WebSocket 프로토콜만 가능
실시간이 아닌 통신에 적합하지 않습니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
WebSocket Client
A simple WebSocket client for Dart which includes automatic reconnection
logic.
Quick Start 🚀
// Create a WebSocket client.final socket = WebSocket(Uri.parse('ws://localhost:8080'));
// Listen to messages from the server.
socket.messages.listen((message) {
// Handle incoming messages.
});
// Send a message to the server.
socket.send('ping');
// Close the connection.
socket.close();
Establishing a Connection 🔌
The WebSocket client will attempt to establish a connection immediately upon
initialization. By default, a timeout will occur if establishing a connection
exceeds 60 seconds but a custom timeout duration can be provided:
final uri = Uri.parse('ws://localhost:8080');
// Trigger a timeout if establishing a connection exceeds 10s.final timeout = Duration(seconds: 10);
final socket = WebSocket(uri, timeout: timeout);
Reconnecting 🔄
If the WebSocket client is not able to establish a connection, it will
automatically attempt to reconnect using the provided Backoff strategy. By
default, a BinaryExponentialBackoff is used but a custom backoff can be
provided.
There are three built-in backoff strategies but a custom backoff strategy can be
written by implementing the Backoff interface.
ConstantBackoff
This backoff strategy will make the WebSocket client wait a constant amount of
time between reconnection attempts.
// Wait a constant 1s between reconnection attempts.// [1, 1, 1, ...]const backoff = ConstantBackoff(Duration(seconds: 1));
final socket = WebSocket(uri, backoff: backoff);
LinearBackoff
This backoff strategy will make the WebSocket client wait a linearly
increasing amount of time until an optional maximum duration is reached.
// Initially wait 0s and increase the wait time by 1s until a maximum of 5s is reached.// [0, 1, 2, 3, 4, 5, 5, 5, ...]const backoff = LinearBackoff(
initial: Duration(seconds: 0),
increment: Duration(seconds: 1),
maximum: Duration(seconds: 5),
);
final socket = WebSocket(uri, backoff: backoff);
BinaryExponentialBackoff
This backoff strategy will make the WebSocket client wait an exponentially
increasing amount of time until a maximum step is reached.
// Initially wait 1s and double the wait time until a maximum step of of 3 is reached.// [1, 2, 4, 4, 4, ...]const backoff = BinaryExponentialBackoff(
initial: Duration(seconds: 1),
maximumStep: 3
);
final socket = WebSocket(uri, backoff: backoff);
Monitoring the Connection ⚡️
The WebSocket client exposes a connection object which can be used to query
the connection state at any given time as well as listen to real-time changes in
the connection state.
final uri = Uri.parse('ws://localhost:8080');
final socket = WebSocket(uri);
// Listen to changes in the connection state.
socket.connection.listen((state) {
// Handle changes in the connection state.
});
// Query the current connection state.final connectionState = socket.connection.state;
The connection state can be one of the following:
connecting: the connection has not yet been established.
connected: the connection is established and communication is possible.
reconnecting: the connection was lost and is in the process of being
re-established.
reconnected: the connection was lost and has been re-established.
disconnecting: the connection is going through the closing handshake or
the close method has been invoked.
disconnected: the WebSocket connection has been closed or could not be
established.
* The disconnected connection state contains nullable fields for the close
code, close reason, error, and stack trace.
Sending Messages 📤
Once a WebSocket connection has been established, messages can be sent to the
server via send:
final socket = WebSocket(Uri.parse('ws://localhost:8080'));
// Wait until a connection has been established.await socket.connection.firstWhere((state) => state isConnected);
// Send a message to the server.
socket.send('ping');
Receiving Messages 📥
Listen for incoming messages from the server via the messages stream:
final socket = WebSocket(Uri.parse('ws://localhost:8080'));
// Listen for incoming messages.
socket.messages.listen((message) {
// Handle the incoming message.
});
Protobuf 💬
If you're using web_socket_client on the web with Protobuf, you might
want to use binaryType when initializing the WebSocket class.
binaryType is only applicable on the web and is not used on desktop or mobile platforms.
final socket = WebSocket(Uri.parse('ws://localhost:8080'), binaryType: 'arraybuffer');
See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/binaryType for more info.
Closing the Connection 🚫
Once a WebSocket connection is established, it will automatically attempt to
reconnect if the connection is disrupted. Calling close() will update the
connection state to disconnecting, perform the closing handshake, and set the
state to disconnected. At this point, the WebSocket client will not attempt
to reconnect and a new WebSocket client instance will need to be created in
order to establish a new connection.
final socket = WebSocket(Uri.parse('ws://localhost:8080'));
// Later, close the connection with an optional code and reason.
socket.close(1000, 'CLOSE_NORMAL');