From 8a0139640c0a9fe5176a485ea91c322ad86d2d5a Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 13 Dec 2022 03:36:22 +0100 Subject: [PATCH] Add server password for connection, and change reconnect handling. --- lib/chessapp/chess_app.dart | 2 +- lib/connection/ws_connection.dart | 16 ++++++++++++---- lib/connection_cubit/connection_cubit.dart | 3 +++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/chessapp/chess_app.dart b/lib/chessapp/chess_app.dart index eefffb1..9dbcce7 100644 --- a/lib/chessapp/chess_app.dart +++ b/lib/chessapp/chess_app.dart @@ -51,6 +51,7 @@ class ChessApp extends StatelessWidget { return StreamBuilder( stream: ServerConnection.getInstance().channel.stream, builder: (context, snapshot) { + print(snapshot.data.toString()); return Text( style: const TextStyle(color: Colors.white), snapshot.data.toString()); @@ -65,7 +66,6 @@ class ChessApp extends StatelessWidget { ), floatingActionButton: FloatingActionButton( onPressed: () { - ServerConnection.getInstance().reconnect(); ConnectionCubit.getInstance().reconnect(); }, child: const Icon(Icons.network_wifi), diff --git a/lib/connection/ws_connection.dart b/lib/connection/ws_connection.dart index ebe1715..a62602f 100644 --- a/lib/connection/ws_connection.dart +++ b/lib/connection/ws_connection.dart @@ -2,15 +2,14 @@ import 'package:web_socket_channel/web_socket_channel.dart'; class ServerConnection { late WebSocketChannel channel; + late bool wasConnected = false; late int counter = 0; static final ServerConnection _instance = ServerConnection._internal(); ServerConnection._internal() { print("ServerConnection._interal constructor is called"); - channel = WebSocketChannel.connect( - Uri.parse('ws://localhost:8080'), - ); + connect(); } factory ServerConnection() { @@ -26,7 +25,16 @@ class ServerConnection { counter++; } - void reconnect() { + void connect() { + if (wasConnected) channel.sink.close(); channel = WebSocketChannel.connect(Uri.parse('ws://localhost:8080')); + wasConnected = true; + + sendPassword(); + } + + void sendPassword() { + channel.sink.add( + 'pw NC4EjHvRcsltY3ibWuYDH9OXbKgDXppfnHNCi1K4jktMspoeZjBnOPExxCpDms7zmxijoKCSaSlZ1fWclfWr7Q32DJnv2k87Z5uM'); } } diff --git a/lib/connection_cubit/connection_cubit.dart b/lib/connection_cubit/connection_cubit.dart index 74d699a..7a9cef8 100644 --- a/lib/connection_cubit/connection_cubit.dart +++ b/lib/connection_cubit/connection_cubit.dart @@ -1,5 +1,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; +import '../connection/ws_connection.dart'; + class ConnectionCubit extends Cubit { static final ConnectionCubit _instance = ConnectionCubit._internal(); @@ -14,6 +16,7 @@ class ConnectionCubit extends Cubit { } void reconnect() { + ServerConnection.getInstance().connect(); emit(ConnectionCubitState(true)); } }