pub struct RawClient { /* private fields */ }
Expand description

A socket which 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 "/".

Implementations§

Sends a message to the server using the underlying engine.io protocol. This message takes an event, which could either be one of the common events like “message” or “error” or a custom event like “foo”. But be careful, the data string needs to be valid JSON. It’s recommended to use a library like serde_json to serialize the data properly.

Example
use rust_socketio::{ClientBuilder, RawClient, Payload};
use serde_json::json;

let mut socket = ClientBuilder::new("http://localhost:4200/")
    .on("test", |payload: Payload, socket: RawClient| {
        println!("Received: {:#?}", payload);
        socket.emit("test", json!({"hello": true})).expect("Server unreachable");
     })
    .connect()
    .expect("connection failed");

let json_payload = json!({"token": 123});

let result = socket.emit("foo", json_payload);

assert!(result.is_ok());
Examples found in repository?
examples/callback.rs (line 5)
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
fn handle_foo(payload: Payload, socket: RawClient) -> () {
    socket.emit("bar", payload).expect("Server unreachable")
}

fn main() {
    // define a callback which is called when a payload is received
    // this callback gets the payload as well as an instance of the
    // socket to communicate with the server
    let handle_test = |payload: Payload, socket: RawClient| {
        match payload {
            Payload::String(str) => println!("Received string: {}", str),
            Payload::Binary(bin_data) => println!("Received bytes: {:#?}", bin_data),
        }
        socket
            .emit("test", json!({"got ack": true}))
            .expect("Server unreachable")
    };

    // get a socket that is connected to the admin namespace
    let socket = ClientBuilder::new("http://localhost:4200")
        .namespace("/admin")
        // Saved closure
        .on("test", handle_test)
        // Inline closure
        .on("error", |err, _| eprintln!("Error: {:#?}", err))
        // Function call with signature (payload: Payload, socket: RawClient) -> ()
        .on("foo", handle_foo)
        // Reserved event names are case insensitive
        .on("oPeN", |_, _| println!("Connected"))
        // Custom names are case sensitive
        .on("Test", |_, _| println!("TesT received"))
        // Event specified by enum
        .on(Event::Close, |_, socket| {
            println!("Socket Closed");
            socket
                .emit("message", json!({"foo": "Hello server"}))
                .expect("Error emitting");
        })
        .connect()
        .expect("Connection failed");

    // use the socket

    socket.disconnect().expect("Disconnect failed")
}
More examples
Hide additional examples
examples/readme.rs (line 15)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn main() {
    // define a callback which is called when a payload is received
    // this callback gets the payload as well as an instance of the
    // socket to communicate with the server
    let callback = |payload: Payload, socket: RawClient| {
        match payload {
            Payload::String(str) => println!("Received: {}", str),
            Payload::Binary(bin_data) => println!("Received bytes: {:#?}", bin_data),
        }
        socket
            .emit("test", json!({"got ack": true}))
            .expect("Server unreachable")
    };

    // get a socket that is connected to the admin namespace
    let socket = ClientBuilder::new("http://localhost:4200")
        .namespace("/admin")
        .on("test", callback)
        .on("error", |err, _| eprintln!("Error: {:#?}", err))
        .connect()
        .expect("Connection failed");

    // emit to the "foo" event
    let json_payload = json!({"token": 123});
    socket
        .emit("foo", json_payload)
        .expect("Server unreachable");

    // define a callback, that's executed when the ack got acked
    let ack_callback = |message: Payload, _| {
        println!("Yehaa! My ack got acked?");
        println!("Ack data: {:#?}", message);
    };

    let json_payload = json!({"myAckData": 123});
    // emit with an ack

    socket
        .emit_with_ack("test", json_payload, Duration::from_secs(2), ack_callback)
        .expect("Server unreachable");

    socket.disconnect().expect("Disconnect failed")
}

Disconnects this client from the server by sending a socket.io closing packet.

Example
use rust_socketio::{ClientBuilder, Payload, RawClient};
use serde_json::json;

fn handle_test(payload: Payload, socket: RawClient) {
    println!("Received: {:#?}", payload);
    socket.emit("test", json!({"hello": true})).expect("Server unreachable");
}

let mut socket = ClientBuilder::new("http://localhost:4200/")
    .on("test", handle_test)
    .connect()
    .expect("connection failed");

let json_payload = json!({"token": 123});

socket.emit("foo", json_payload);

// disconnect from the server
socket.disconnect();

Sends a message to the server but allocs an ack to check whether the server responded in a given time span. This message takes an event, which could either be one of the common events like “message” or “error” or a custom event like “foo”, as well as a data parameter. But be careful, in case you send a Payload::String, the string needs to be valid JSON. It’s even recommended to use a library like serde_json to serialize the data properly. It also requires a timeout Duration in which the client needs to answer. If the ack is acked in the correct time span, the specified callback is called. The callback consumes a Payload which represents the data send by the server.

Example
use rust_socketio::{ClientBuilder, Payload, RawClient};
use serde_json::json;
use std::time::Duration;
use std::thread::sleep;

let mut socket = ClientBuilder::new("http://localhost:4200/")
    .on("foo", |payload: Payload, _| println!("Received: {:#?}", payload))
    .connect()
    .expect("connection failed");

let ack_callback = |message: Payload, socket: RawClient| {
    match message {
        Payload::String(str) => println!("{}", str),
        Payload::Binary(bytes) => println!("Received bytes: {:#?}", bytes),
   }
};

let payload = json!({"token": 123});
socket.emit_with_ack("foo", payload, Duration::from_secs(2), ack_callback).unwrap();

sleep(Duration::from_secs(2));

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more