Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help #445

Open
AriBermeki opened this issue Jun 29, 2024 · 0 comments
Open

Help #445

AriBermeki opened this issue Jun 29, 2024 · 0 comments

Comments

@AriBermeki
Copy link

AriBermeki commented Jun 29, 2024

can someone please help me I get a compiler error and I don't know exactly what happened because I'm just learning rust

use rust_socketio::{ClientBuilder, Payload, RawClient};
use serde_json::json;
use tao::event_loop::EventLoopProxy;
use std::time::Duration;
use tokio::io::{self, AsyncBufReadExt};
use tokio::task;

use crate::structs::UserEvent;

pub async fn send_message(message: String, proxy: &EventLoopProxy<UserEvent>) {
    match serde_json::from_str::<serde_json::Value>(&message.trim()) {
        Ok(_) => {
            proxy.send_event(UserEvent::NewMessageReceived(message)).unwrap_or_default();
        }
        Err(_) => {
            proxy
                .send_event(UserEvent::NewMessageReceived(
                    json!({ "error": "Invalid JSON" }).to_string(),
                ))
                .unwrap_or_default();
        }
    }
}

pub async fn run_listener(
    proxy: &EventLoopProxy<UserEvent>,
) -> Result<(), Box<dyn std::error::Error>> {
    let stdin = io::stdin();
    let mut reader = io::BufReader::new(stdin);

    loop {
        let mut line = String::new();

        // Read from stdin asynchronously
        let bytes_read = reader.read_line(&mut line).await?;
        if bytes_read == 0 {
            // No bytes read, so EOF has been reached
            return Ok(());
        } else {
            send_message(line, proxy).await;
        }
    }
}

pub async fn initialize_socket_connections(
    proxy: EventLoopProxy<UserEvent>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Callback for received messages
    let message_callback = move |payload: Payload, socket: RawClient| {
        let proxy_clone = proxy.clone();
        task::spawn(async move {
            // -------------------------- Error---------------------------
            match payload {  
                Payload::Text(str) => {
                    println!("Received: {}", str);
                    
                }
                Payload::Binary(bin_data) => {
                    println!("Received bytes: {:#?}", bin_data);
                }
            }
            // -----------------------------------------------------------

            proxy_clone.send_event(UserEvent::NewSocketMessageReceived(payload)).unwrap_or_default();
            if let Err(e) = socket.emit("message", json!({"message ": "Hallo python from rust"})) {
                eprintln!("Failed to send ack: {:?}", e);
            }
        });
    };

    // Callback for errors
    let error_callback = |err, _| eprintln!("Error: {:#?}", err);
    // -------------------------- Error---------------------------
    // Create the Socket.IO client
    let socket = ClientBuilder::new("http://localhost:8000")
        .on("message", message_callback)
        .on("error", error_callback)
        .connect()
        .await;

    // -----------------------------------------------------------
    tokio::time::sleep(Duration::from_secs(10)).await;

    // Disconnect the socket
    socket.disconnect().map_err(|e| eprintln!("Failed to disconnect: {:?}", e)).ok();

    Ok(())
}


import socketio
from socketio import ASGIApp
import uvicorn

# Erstellen eines Socket.IO-Servers
sio = socketio.AsyncServer()
app = ASGIApp(sio)

# Ereignis-Handler für die Verbindung
@sio.event
async def connect(sid, environ):
    print('Client connected:', sid)
    await sio.emit('message', {'data': 'Welcome!'}, to=sid)

# Ereignis-Handler für Nachrichten
@sio.event
async def message(sid, data):
    print('Message from', sid, ':', data)
    await sio.emit('message', {'data': 'Echo: ' + data['data']}, to=sid)

# Ereignis-Handler für die Trennung
@sio.event
async def disconnect(sid):
    print('Client disconnected:', sid)

# Starten des ASGI-Servers
if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=8000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant