mchess-client/lib/connection/ws_connection.dart

82 lines
2.1 KiB
Dart
Raw Normal View History

import 'dart:developer';
import 'dart:io';
2022-12-18 22:06:55 +00:00
import 'package:flutter/foundation.dart';
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 {
2022-12-18 00:04:08 +00:00
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) {
2022-12-18 00:04:08 +00:00
channel.sink.add(message);
counter++;
}
2022-11-19 12:24:38 +00:00
void connect() {
2022-12-18 00:04:08 +00:00
if (wasConnected) channel.sink.close();
2022-12-18 22:06:55 +00:00
if (kDebugMode) {
channel = WebSocketChannel.connect(Uri.parse('ws://localhost:8080'));
} else {
channel =
WebSocketChannel.connect(Uri.parse('wss://chess.sw-gross.de:8080'));
}
log(channel.closeCode.toString());
wasConnected = true;
2022-12-18 00:04:08 +00:00
broadcast = channel.stream.asBroadcastStream();
broadcast.listen((data) {
log("Data received:");
log(data);
var receivedString = data.toString();
2022-12-18 00:04:08 +00:00
var splitString = receivedString.split(' ');
2022-12-18 00:04:08 +00:00
if (splitString[0] == "cl") {
ChessColor onBottom =
splitString[1] == "white" ? ChessColor.white : ChessColor.black;
ChessBloc.getInstance().add(ColorDetermined(myColor: onBottom));
return;
}
2022-12-18 00:04:08 +00:00
if (splitString[0] == "bd") {
if (splitString[1] == "init") ChessBloc.getInstance().add(InitBoard());
}
if (splitString[0] == ('mv')) {
var startSquare = ChessCoordinate.fromString(splitString[1]);
var endSquare = ChessCoordinate.fromString(splitString[2]);
log('Move received : ${splitString[1]}:${splitString[2]}');
ChessBloc.getInstance()
.add(PieceMoved(startSquare: startSquare, endSquare: endSquare));
}
});
2022-11-19 12:24:38 +00:00
}
}