start method
Starts the WebSocket server and begins listening for connections.
This method binds the server to the specified port and listens for HTTP upgrade requests to WebSocket connections. When a valid WebSocket connection is established, the client is added to the list of connected clients.
Throws an IOException if the server fails to bind to the specified port.
Implementation
Future<void> start() async {
_server = await HttpServer.bind(InternetAddress.anyIPv4, port);
debugPrint(
'WebSocket server started on ws://${_server!.address.address}:${_server!.port}');
await for (HttpRequest request in _server!) {
if (WebSocketTransformer.isUpgradeRequest(request)) {
WebSocket socket = await WebSocketTransformer.upgrade(request);
debugPrint('Audio Client connected: ${socket.hashCode}');
_clients.add(socket);
audioClientListCallBack(_clients);
_handleConnection(socket);
socket.pingInterval = const Duration(seconds: 5);
} else {
request.response
..statusCode = HttpStatus.forbidden
..write('WebSocket connections only.')
..close();
}
}
}