8271_ANURAG_KANADE
8271_ANURAG_KANADE

Reputation: 1

connect two different Devices (android and chrome) with same wifi and then send messages from android to the web

My task is to send the message from android and receiving the the message to Web Chrome through wifi connectivity. The wifi network should be same for both devices.

I used UDP but it does not support for the chrome. So I switched to the WebSocketChannel in which I set the port to be static by the terminal command flutter run -d chrome --web-port 1234. Instead of 1234 I used to change the port number by myself.

My code

try {
  channel = WebSocketChannel.connect(Uri.parse(webSocketUrl));
  logger.i("WebSocket connected to $webSocketUrl");
  return channel;
} catch (e) {
  logger.e("Error connecting to WebSocket: $e");
  return null;
}

To send message:

if (channel == null) {
  logger.e("WebSocket channel is not initialized.");
  return;
} else {
  try {
    channel.sink.add(message);
    log("Sending message: $message");
  } catch (e) {
    logger.e("Error sending message: $e");
  }
}

To receive the message:

if (channel == null) {
  logger.e("WebSocket channel is not initialized.");
  return;
} else {
  channel.stream.listen(
    (message) {
      runInAction(() {
        receivedMessage = message;
        log("Received message: $receivedMessage");
        logger.i("Received message: $receivedMessage");`your text`
      });
    },
    onError: (error) {
      logger.e("Error receiving message: $error");
    },
    onDone: () {
      logger.i("WebSocket connection closed.");
    }
  );
}

Upvotes: 0

Views: 20

Answers (0)

Related Questions