Websocket support

pub package web_socket_support codecov

A Flutter plugin for websockets on Android (currently). This plugin is based on okHttp (for Android platform).

Plugin was created as an attempt to overcome shortcomings of Flutter standard WebSocket implementation (cookbook) like connection not staying open while screen is locked or the application is in background. This plugin solves these problems.

Introduction

Websocket support uses Platform Channel to expose Dart APIs that Flutter application can use to communicate with platform specific websocket native libraries. For andorid, chosen java Websocket implementation is OkHttp.

Example

// WebSocketConnection will be obtained via _onWsOpen callback in WebSocketClient
WebSocketConnection _webSocketConnection;

// instantiate WebSocketClient with DefaultWebSocketListener and some callbacks
// Of course you can use you own WebSocketListener implementation
final WebSocketClient _wsClient = WebSocketClient(DefaultWebSocketListener.forTextMessages(
        (wsc) => _webSocketConnection = wsc,                       // _onWsOpen callback
        (code, msg) => print('Connection closed. Reason: $msg'),  // _onWsClosed callback
        (msg) => print('Message received: $msg')));               // _onStringMessage callback
// ...
// connect to remote ws endpoint
await _wsClient.connect('ws://echo.websocket.org', options: WebSocketOptions(autoReconnect: true);

// ...
// After connection is established, use obtained WebSocketConnection instance to send messages
_webSocketConnection.sendTextMessage('Hello from Websocket support');

or see example for more details.

Build Dependencies

  • Dart SDK version: >=2.16.0 <4.0.0
  • Flutter SDK version: >=2.10.0
  • Java version: 11
  • AGP version: 8.7.x
  • Gradle version: 8.9.x
  • Android SDK min version: 27
  • Android SDK target version: 34

TODO

Unfortunately, iOS implementation is still missing. So, if you have know-how, and you're willing to implement it - you will be more than welcomed. Preffered WebSocket libs are NWWebSocket and Starscream, but we are opened for other options as well.

Contributing

See the Contributing guide for details on contributing to this project.

Libraries

web_socket_support