Reputation: 1
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