Initial web socket client support
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:frontend/providers/dio.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shared_models/room.dart';
|
||||
|
||||
part 'game_messages.g.dart';
|
||||
|
||||
@riverpod
|
||||
class GameMessageNotifier extends _$GameMessageNotifier {
|
||||
@override
|
||||
Stream<GameRoomMessage> build() {
|
||||
return Stream.empty();
|
||||
}
|
||||
|
||||
Future<void> connect(String gameRoomUuid) async {
|
||||
final dio = ref.read(dioProvider);
|
||||
Uri.parse('ws://localhost:8080/room/$gameRoomUuid/ws');
|
||||
|
||||
// connect to websocket and then set stream of websocket to state
|
||||
final wsUrl = Uri.parse('ws://localhost:8080/room/$gameRoomUuid/ws');
|
||||
|
||||
final connection = await WebSocket.connect(wsUrl.toString());
|
||||
|
||||
final Stream<GameRoomMessage> gameRoomStream = connection.map((message) {
|
||||
try {
|
||||
if (message is String) {
|
||||
GameRoomMessage.fromJson(jsonDecode(message) as Map<String, dynamic>);
|
||||
} else {
|
||||
logger.info('Recieved non-string message in socket: $message');
|
||||
}
|
||||
} catch (e) {
|
||||
print('Error parsing message: $e');
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
gameRoomStream.listen(
|
||||
(event) => state = AsyncValue.data(event),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user