Add server password for connection, and change reconnect handling.

This commit is contained in:
Marco 2022-12-13 03:36:22 +01:00
parent 3889245c8a
commit 8a0139640c
3 changed files with 16 additions and 5 deletions

View File

@ -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),

View File

@ -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');
}
}

View File

@ -1,5 +1,7 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../connection/ws_connection.dart';
class ConnectionCubit extends Cubit<ConnectionCubitState> {
static final ConnectionCubit _instance = ConnectionCubit._internal();
@ -14,6 +16,7 @@ class ConnectionCubit extends Cubit<ConnectionCubitState> {
}
void reconnect() {
ServerConnection.getInstance().connect();
emit(ConnectionCubitState(true));
}
}