start method

Future<void> start()

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

  // Listen for incoming HTTP requests.
  await for (HttpRequest request in _server!) {
    if (WebSocketTransformer.isUpgradeRequest(request)) {
      // Upgrade the HTTP request to a WebSocket connection.
      WebSocket socket = await WebSocketTransformer.upgrade(request);
      _handleConnection(socket); // Handle the newly established connection.
    } else {
      // Reject non-WebSocket requests.
      request.response
        ..statusCode = HttpStatus.forbidden
        ..write('WebSocket connections only.')
        ..close();
    }
  }
}