All dem changes

This commit is contained in:
ImBenji
2024-05-24 20:17:02 +01:00
parent 2846a061cc
commit ffde62a730
13 changed files with 990 additions and 195 deletions

View File

@@ -9,11 +9,16 @@ import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:bus_infotainment/backend/modules/info_module.dart';
import 'package:bus_infotainment/utils/delegates.dart';
import 'package:http/http.dart' as http;
class NetworkingModule extends InfoModule {
// Host websocket server
String host = "ws://0.0.0.0:8080";
HttpServer? _server;
int webSocketPort = 8080;
int httpPort = 8081;
HttpServer? _sockerServer;
HttpServer? _httpServer;
WebSocketChannel? _channel;
// Store connected WebSocket channels
@@ -50,8 +55,13 @@ class NetworkingModule extends InfoModule {
});
});
_server = await io.serve(handler, InternetAddress.anyIPv4, 8080);
print('WebSocket server started at ${_server?.address.address}:${_server?.port}');
_sockerServer = await io.serve(handler, InternetAddress.anyIPv4, webSocketPort);
print('WebSocket server started at ${_sockerServer?.address.address}:${_sockerServer?.port}');
// Start Http api server
_httpServer = await io.serve((Request request) async {
return Response.ok('bus infotainment server');
}, InternetAddress.anyIPv4, httpPort);
return true;
} catch (e) {
@@ -61,7 +71,7 @@ class NetworkingModule extends InfoModule {
}
bool stopWebSocketServer() {
if (_server == null) {
if (_sockerServer == null) {
throw Exception('WebSocket server is not running');
}
@@ -70,8 +80,12 @@ class NetworkingModule extends InfoModule {
client.sink.close();
}
_connectedClients.clear();
_server?.close(force: true);
_server = null;
_sockerServer?.close(force: true);
_sockerServer = null;
_httpServer?.close(force: true);
_httpServer = null;
print('WebSocket server stopped');
return true;
} catch (e) {
@@ -82,6 +96,17 @@ class NetworkingModule extends InfoModule {
Future<bool> connectToWebSocketServer(String url) async {
try {
{
// Verify that the server we are connecting to is running, and is a bus infotainment server
var response = await http.get(Uri.parse('http://$url:$httpPort'));
if (response.statusCode != 200 || response.body != 'bus infotainment server') {
print('Server at $url is not a bus infotainment server');
return false;
}
}
_channel = await WebSocketChannel.connect(Uri.parse(url));
_channel?.stream.listen((message) {
// Handle messages from the server here
@@ -116,7 +141,7 @@ class NetworkingModule extends InfoModule {
bool sendMessage(String message) {
// If hosting a server, send message to all clients
if (_server != null) {
if (_sockerServer != null) {
return sendMessageToClients(message);
}
@@ -193,4 +218,4 @@ class NetworkingModule extends InfoModule {
}
}
}
}
}