import 'dart:developer'; import 'package:mchess/chess_bloc/chess_bloc.dart'; import 'package:mchess/chess_bloc/chess_events.dart'; import 'package:mchess/chessapp/chess_utils.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; class ServerConnection { late WebSocketChannel channel; late bool wasConnected = false; late int counter = 0; late Stream broadcast; static final ServerConnection _instance = ServerConnection._internal(); ServerConnection._internal() { log("ServerConnection._internal constructor is called"); connect(); } factory ServerConnection() { return _instance; } factory ServerConnection.getInstance() { return ServerConnection(); } void send(String message) { channel.sink.add(message); counter++; } void connect() { if (wasConnected) channel.sink.close(); channel = WebSocketChannel.connect(Uri.parse('wss://chess.sw-gross.de:8080')); log(channel.closeCode.toString()); wasConnected = true; broadcast = channel.stream.asBroadcastStream(); broadcast.listen((data) { log("Data received:"); log(data); var receivedString = data.toString(); var splitString = receivedString.split(' '); if (splitString[0] == "cl") { ChessColor onBottom = splitString[1] == "white" ? ChessColor.white : ChessColor.black; ChessBloc.getInstance().add(ColorDetermined(myColor: onBottom)); return; } if (splitString[0] == "bd") { if (splitString[1] == "init") ChessBloc.getInstance().add(InitBoard()); } if (splitString[1] == ('mv')) { var startSquare = ChessCoordinate.fromString(splitString[2]); var endSquare = ChessCoordinate.fromString(splitString[3]); log('Move received : ${splitString[2]}:${splitString[3]}'); ChessBloc.getInstance() .add(PieceMoved(startSquare: startSquare, endSquare: endSquare)); } }); } }