import 'package:socket_io_client/socket_io_client.dart';
import '../../config.dart';
import '../showSnack.dart';
class DataStreamBloc {
final _stateStreamController = StreamController<Map>();
StreamSink<Map> get dataSink => _stateStreamController.sink;
Stream<Map> get dataStream => _stateStreamController.stream;
}
StreamController<Map> controller = StreamController<Map>.broadcast();
Stream stream = controller.stream;
final dataStreamBloc = DataStreamBloc();
registerToken(context) async {
var token = await readToken();
if (token.isNotEmpty) {
Socket socket = io(
'http://localhost:4400/api/ws'
,
OptionBuilder()
// .setTransports(['websocket']) // for Flutter or Dart VM
.enableReconnection()
.enableAutoConnect() // disable auto-connection
.setQuery({'token': '$token'})
.disableForceNew()
.disableForceNewConnection()
.disableMultiplex()
.setReconnectionDelay(10) // optional
.build());
print(socket.connected);
if (socket.connected == false) {
socket.connect();
}
socket.on('fromServer', (data) {
print('fromServer: ' + data.toString());
});
socket.on('serverData', (data) {
if (data.runtimeType.toString() == 'String') {
var dataDecoded = jsonDecode(data.toString());
Map dataMapped = json.decode(dataDecoded);
var type = dataMapped['type'];
var from = dataMapped['from'];
var task = dataMapped['task'];
print(dataMapped['task']);
print(dataMapped);
dataStreamBloc.dataSink.add(dataMapped);
controller.add(dataMapped);
if (type == "sessionRequest") {
showSnack(context, 'Do you wish to accept a call from $from?');
}
if (type == "message") {
showSnack(context, 'new message from $from');
}
return data;
}
});
} else {
print('token is missing, ask the user to log back in again');
}
}
I am using getToken(context) within an init state to call socket.io, client seems to connect multiple times and that is what is causing a repeat of the information being received, on the server side I use the token to auth them and put them inside of a channel where I can then broadcast to that channel for any updates that the server has for a client. I am using socket.io for notifications and chat request. I know it is on the client side because on there server it only shows the broadcast function getting hit once. How do I make sure that this client only connects when there is not an active socket.io stream already connected? Thanks!