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

Implement shared custom data (re-worked) based on the previous work from kitgxrl #435

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
[workspace]
members = ["engineio", "socketio"]
resolver = "2"
2 changes: 1 addition & 1 deletion engineio/src/asynchronous/client/async_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ impl Debug for Client {
}
}

#[cfg(all(test))]
#[cfg(test)]
mod test {

use super::*;
Expand Down
2 changes: 1 addition & 1 deletion engineio/src/asynchronous/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub mod async_transports;
pub mod transport;

pub(self) mod async_socket;
mod async_socket;
#[cfg(feature = "async-callbacks")]
mod callback;
#[cfg(feature = "async")]
Expand Down
5 changes: 2 additions & 3 deletions engineio/src/client/client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use super::super::socket::Socket as InnerSocket;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please keep this code in client.rs? I assume this was to fix the client/client clippy lint? :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it was to fix the lint, I figured since the lint was enabled that it just hadn't got around to being fixed yet, I can put the code back, and disable the lint.

use crate::callback::OptionalCallback;
use crate::socket::DEFAULT_MAX_POLL_TIMEOUT;
use crate::transport::Transport;

use crate::error::{Error, Result};
use crate::header::HeaderMap;
use crate::packet::{HandshakePacket, Packet, PacketId};
use crate::socket::DEFAULT_MAX_POLL_TIMEOUT;
use crate::transport::Transport;
use crate::transports::{PollingTransport, WebsocketSecureTransport, WebsocketTransport};
use crate::ENGINE_IO_VERSION;
use bytes::Bytes;
Expand Down
1 change: 1 addition & 0 deletions engineio/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(clippy::module_inception)]
mod client;
pub use client::Iter;
pub use {client::Client, client::ClientBuilder, client::Iter as SocketIter};
2 changes: 1 addition & 1 deletion engineio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub mod client;
/// Generic header map
pub mod header;
pub mod packet;
pub(self) mod socket;
mod socket;
pub mod transport;
pub mod transports;

Expand Down
5 changes: 5 additions & 0 deletions socketio/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,8 @@ async = ["async-callbacks", "rust_engineio/async", "tokio", "futures-util", "asy
name = "async"
path = "examples/async.rs"
required-features = ["async"]

[[example]]
name = "async-transmitter"
path = "examples/async_transmitter.rs"
required-features = ["async"]
112 changes: 112 additions & 0 deletions socketio/examples/async_transmitter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use futures_util::future::{BoxFuture, FutureExt};
use rust_socketio::{
asynchronous::{Client as SocketIOClient, ClientBuilder as SocketIOClientBuilder},
Error as SocketIOError, Payload,
};
use serde_json::{json, Value};
use std::sync::{mpsc, Arc};
use std::time::Duration;
use tokio::time::sleep;

type JsonValues = Vec<Value>;

fn test_event_handler<'event>(payload: Payload, socket: SocketIOClient) -> BoxFuture<'event, ()> {
async move {
if let Payload::Text(values) = payload {
match socket.try_transmitter::<mpsc::Sender<JsonValues>>() {
Ok(tx) => {
tx.send(values.to_owned()).map_or_else(
|err| eprintln!("{}", err),
|_| println!("Data transmitted successfully"),
);
}
Err(err) => {
eprintln!("{}", err);
}
}
}
}
.boxed()
}

fn error_event_handler<'event>(payload: Payload, _: SocketIOClient) -> BoxFuture<'event, ()> {
async move { eprintln!("Error: {:#?}", payload) }.boxed()
}

struct ComplexData {
/// There should be many more fields below in real life,
/// probaly wrapped in Arc<Mutex<T>> if you're writing a more serious client.
data: String,
}

struct TransmitterClient {
receiver: mpsc::Receiver<JsonValues>,
complex: ComplexData,
client: SocketIOClient,
}

impl TransmitterClient {
async fn connect(url: &str) -> Result<Self, SocketIOError> {
let (sender, receiver) = mpsc::channel::<JsonValues>();

let client = SocketIOClientBuilder::new(url)
.namespace("/admin")
.on("test", test_event_handler)
.on("error", error_event_handler)
.transmitter(Arc::new(sender))
.connect()
.await?;

Ok(Self {
client,
receiver,
complex: ComplexData {
data: String::from(""),
},
})
}

async fn get_test(&mut self) -> Option<String> {
match self.client.emit("test", json!({"got ack": true})).await {
Ok(_) => {
match self.receiver.recv() {
Ok(values) => {
// Json deserialization and parsing business logic should be implemented
// here to avoid over-complicating the handler callbacks.
if let Some(value) = values.first() {
if value.is_string() {
self.complex.data = String::from(value.as_str().unwrap());
return Some(self.complex.data.clone());
}
}
None
}
Err(err) => {
eprintln!("Transmission buffer is probably full: {}", err);
None
}
}
}
Err(err) => {
eprintln!("Server unreachable: {}", err);
None
}
}
}
}

#[tokio::main]
async fn main() {
match TransmitterClient::connect("http://localhost:4200/").await {
Ok(mut client) => {
if let Some(test_data) = client.get_test().await {
println!("test event data from internal transmitter: {}", test_data);
}
}
Err(err) => {
eprintln!("Failed to connect to server: {}", err);
}
}

sleep(Duration::from_secs(2)).await;
}
3 changes: 3 additions & 0 deletions socketio/examples/readme.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use rust_socketio::{ClientBuilder, Payload, RawClient};
use serde_json::json;
use std::thread::sleep;
use std::time::Duration;

fn main() {
Expand Down Expand Up @@ -45,5 +46,7 @@ fn main() {
.emit_with_ack("test", json_payload, Duration::from_secs(2), ack_callback)
.expect("Server unreachable");

sleep(Duration::from_secs(2));

socket.disconnect().expect("Disconnect failed")
}
106 changes: 106 additions & 0 deletions socketio/examples/sync_transmitter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use rust_socketio::{
client::Client as SocketIOClient, ClientBuilder as SocketIOClientBuilder,
Error as SocketIOError, Payload, RawClient,
};
use serde_json::{json, Value};
use std::sync::{mpsc, Arc};
use std::thread::sleep;
use std::time::Duration;

type JsonValues = Vec<Value>;

fn test_event_handler(payload: Payload, socket: RawClient) {
if let Payload::Text(values) = payload {
match socket.try_transmitter::<mpsc::Sender<JsonValues>>() {
Ok(tx) => {
tx.send(values.to_owned()).map_or_else(
|err| eprintln!("{}", err),
|_| println!("Data transmitted successfully"),
);
}
Err(err) => {
eprintln!("{}", err);
}
}
}
}

fn error_event_handler(payload: Payload, _: RawClient) {
eprintln!("Error: {:#?}", payload);
}

struct ComplexData {
/// There should be many more fields below in real life,
/// probaly wrapped in Arc<Mutex<T>> if you're writing a more serious client.
data: String,
}

struct TransmitterClient {
client: SocketIOClient,
receiver: mpsc::Receiver<JsonValues>,
complex: ComplexData,
}

impl TransmitterClient {
fn connect(url: &str) -> Result<Self, SocketIOError> {
let (sender, receiver) = mpsc::channel::<JsonValues>();

let client = SocketIOClientBuilder::new(url)
.namespace("/admin")
.on("test", test_event_handler)
.on("error", error_event_handler)
.transmitter(Arc::new(sender))
.connect()?;

Ok(Self {
client,
receiver,
complex: ComplexData {
data: "".to_string(),
},
})
}

fn get_test(&mut self) -> Option<String> {
match self.client.emit("test", json!({"got ack": true})) {
Ok(_) => {
match self.receiver.recv() {
Ok(values) => {
// Json deserialization and parsing business logic should be implemented
// here to avoid over-complicating the handler callbacks.
if let Some(value) = values.first() {
if value.is_string() {
self.complex.data = String::from(value.as_str().unwrap());
return Some(self.complex.data.clone());
}
}
None
}
Err(err) => {
eprintln!("Transmission buffer is probably full: {}", err);
None
}
}
}
Err(err) => {
eprintln!("Server unreachable: {}", err);
None
}
}
}
}

fn main() {
match TransmitterClient::connect("http://localhost:4200/") {
Ok(mut client) => {
if let Some(test_data) = client.get_test() {
println!("test event data from internal transmitter: {}", test_data);
}
}
Err(err) => {
eprintln!("Failed to connect to server: {}", err);
}
}

sleep(Duration::from_secs(2));
}
Loading
Loading