[][src]Crate rust_socketio

Rust socket.io is a socket-io client for the rust programming language.

Example usage

use rust_socketio::Socket;
use serde_json::{Value, json};
 
#[tokio::main]
async fn main() {
    let mut socket = Socket::new(String::from("http://localhost:80"), Some("/admin"));
 
    // callback for the "foo" event
    socket.on("foo", |message| println!("{}", message)).unwrap();
 
    // connect to the server
    socket.connect().await.expect("Connection failed");
 
    // emit to the "foo" event
    let payload = json!({"token": 123});
    socket.emit("foo", payload.to_string()).await.expect("Server unreachable");
 
    // emit with an ack
    let ack = socket.emit_with_ack("foo", payload.to_string(), Duration::from_secs(2)).await.unwrap();
 
    tokio::time::delay_for(Duration::from_secs(2)).await;
 
    // check if ack is present and read the data
    if ack.read().expect("Server panicked anyway").acked {
        println!("{}", ack.read().expect("Server panicked anyway").data.as_ref().unwrap());
    }
}

Current features

This is the first released version of the client, so it still lacks some features that the normal client would provide. First of all the underlying engine.io protocol still uses long-polling instead of websockets. This will be resolved as soon as both the reqwest libary as well as tungsenite-websockets will bump their tokio version to 1.0.0. At the moment only reqwest is used for async long polling. In general the full engine-io protocol is implemented and most of the features concerning the 'normal' socket.io protocol work as well.

Here's an overview of possible use-cases:

  • connecting to a server.
  • register callbacks for the following event types:
    • open
    • close
    • error
    • message
    • custom events like "foo", "on_payment", etc.
  • send json-data to the server (recommended to use serde_json as it provides safe handling of json data).
  • send json-data to the server and receive an ack with a possible message.

What's currently missing is the emitting of binary data - I aim to implement this as soon as possible.

The whole crate is written in asynchronous rust and it's necessary to use tokio, or other executors with this libary to resolve the futures.

Modules

error

Contains the error type that will be returned with every result in this crate. Handles all kind of errors.

socketio

Contains the types and the code concerning the socket.io protocol.

Structs

Socket

A socket that handles communication with the server. It's initialized with a specific address as well as an optional namespace to connect to. If None is given the server will connect to the default namespace "/".