rust-socketio icon indicating copy to clipboard operation
rust-socketio copied to clipboard

Async implementation

Open miguel-arrf opened this issue 2 years ago • 0 comments

I'm trying to use this crate to create a Chat application. I have an iOS application, a Socket.IO server and a Rust backend.

The use case I'm experimenting is as follows:

  • User A and B are using the iOS App.
  • Whenever user A send a message to user B, the message is sent to the Rust backend that then sends a Socket.IO emit event to the other user (user B). This emit event is sent to the user B id.
  • User B is listening for events with his ID.

The first few messages are always sent from the Rust Backend to the Socket.IO server. However, after a few minutes, I'm just receiving an EngineIO Error.

The SocketIO manager is this one:

use anyhow::Result;
use async_trait::async_trait;
use futures_util::FutureExt;
use rust_socketio::asynchronous::{Client, ClientBuilder};
use serde_json::Value;

#[async_trait]
pub trait SocketIOTrait {
    async fn emit(&self, event: &str, payload: Value) -> Result<()>;
}

pub struct SocketIO {
    client: Client,
}

impl SocketIO {
    pub async fn new() -> Self {
        let socket = ClientBuilder::new("http://localhost:3000")
            .on("error", |err, _| {
                async move { eprintln!("Error->: {:#?}", err) }.boxed()
            })
            .transport_type(rust_socketio::TransportType::Websocket)
            .connect()
            .await
            .expect("Connection failed");

        SocketIO { client: socket }
    }
}

#[tonic::async_trait]
impl SocketIOTrait for SocketIO {
    async fn emit(&self, event: &str, payload: Value) -> Result<()> {
        self.client.emit(event, payload).await?;
        Ok(())
    }
}

I created a test endpoint to easily test the connection:

#[tonic::async_trait]
impl MyAPI for MyService {
    async fn test(&self, request: Request<Empty>) -> Result<Response<Empty>, Status> {
        let json_payload = json!({"message": "NEW_MESSAGE"});

        let new_result = self.socket_io.emit("message", json_payload.clone()).await;

        match new_result {
            Ok(_) => println!("OK"),
            Err(err) => {
                println!("ERROR: {}", err);
            }
        }

        Ok(Response::new(Empty {}))
    }

Does anyone knows how to fix this?

miguel-arrf avatar Mar 07 '23 13:03 miguel-arrf