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._interal 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('ws://localhost:8080')); wasConnected = true; broadcast = _channel.stream.asBroadcastStream(); broadcast.listen((data) { log("Data received:"); log(data); var receivedString = data.toString(); if (receivedString == "fb") { ChessBloc.getInstance().add(BoardFlippedEvent()); return; } var moveStringList = receivedString.split(' '); if (moveStringList[1] == ('mv')) { var startSquare = ChessCoordinate.fromString(moveStringList[2]); var endSquare = ChessCoordinate.fromString(moveStringList[3]); log('Move received : ${moveStringList[2]}:${moveStringList[3]}'); ChessBloc.getInstance() .add(PieceMoved(startSquare: startSquare, endSquare: endSquare)); } }); sendPassword(); } void sendPassword() { send( 'pw NC4EjHvRcsltY3ibWuYDH9OXbKgDXppfnHNCi1K4jktMspoeZjBnOPExxCpDms7zmxijoKCSaSlZ1fWclfWr7Q32DJnv2k87Z5uM'); } }