Advanced web socket based on web_socket_channel.
- Add this to your pubspec.yaml file:
dependencies:
better_web_socket: ^1.0.1
- Install it
$ flutter packages get
void receiveData(BuildContext context) {
MyWebSocketController controller = context.read<MyWebSocketController>();
receiveDataSubscription?.cancel();
receiveDataSubscription = controller.receiveDataStream.listen((data) {
int clientRequestId = parse(data).clientRequestId; // TODO clientRequestId from server
controller.handleSendDataResponse(clientRequestId, BetterWebSocketSendDataResponseState.SUCCESS);
});
sendDataResponseStateSubscription?.cancel();
sendDataResponseStateSubscription = controller.sendDataResponseStateStream.listen((data) {
int clientRequestId = data.item1;
if (clientRequestIdList.contains(clientRequestId)) {
clientRequestIdList.remove(clientRequestId);
String result = "";
switch (data.item2) {
case BetterWebSocketSendDataResponseState.SUCCESS:
result = "send data success";
break;
case BetterWebSocketSendDataResponseState.FAIL:
result = "send data failure";
break;
case BetterWebSocketSendDataResponseState.TIMEOUT:
result = "send data timeout";
break;
}
print(result);
}
});
}
void connect(BuildContext context) {
context.read<DeviceWebSocketController>().startWebSocketConnect(retryCount: double.maxFinite.toInt());
}
void disconnect(BuildContext context, Duration duration) {
context.read<DeviceWebSocketController>().stopWebSocketConnectAfter(duration: duration);
}
void sendData() {
context.read<DeviceWebSocketController>().sendDataAndWaitResponse(clientRequestId, data, retryCount: 3);
}
- reconnect
- delay disconnect
- simulate HTTP request
- auto login when socket connected