mchess-client/lib/connection/ws_connection.dart

72 lines
1.8 KiB
Dart
Raw Normal View History

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++;
}
2022-11-19 12:24:38 +00:00
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');
2022-11-19 12:24:38 +00:00
}
}