-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
433 additions
and
217 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
[package] | ||
name = "threadsafe_zmq" | ||
version = "1.0.0" | ||
version = "1.0.1" | ||
edition = "2021" | ||
authors = ["Elvis Sabanovic <[email protected]>"] | ||
description = "Threadsafe zeromq" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,67 @@ | ||
use env_logger; | ||
use crate::utils::to_string; | ||
use log::{error, info}; | ||
use rand::Rng; | ||
use zmq::Context; | ||
|
||
mod utils; | ||
|
||
fn main() { | ||
env_logger::init(); | ||
|
||
let clients = 4; | ||
let mut handles = Vec::with_capacity(clients); | ||
let addr = "tcp://localhost:5555"; | ||
let ctx = Context::new(); | ||
let socket = ctx | ||
.socket(zmq::DEALER) | ||
.expect("Failed to create DEALER socket"); | ||
|
||
for i in 0..clients { | ||
let client_id = i; | ||
let handle = std::thread::spawn(move || { | ||
let addr = "tcp://localhost:5555"; | ||
let ctx = Context::new(); | ||
let socket = ctx | ||
.socket(zmq::DEALER) | ||
.expect("Failed to create PAIR socket"); | ||
let id = format!("Client-{}", 1); | ||
socket | ||
.set_identity(id.clone().as_bytes()) | ||
.expect("Failed to set identity"); | ||
socket.connect(addr).expect("Failed to connect to server"); | ||
|
||
let rand_id = client_id as u8 + generate_random_number(); | ||
let id = format!("client-{}", rand_id); | ||
socket | ||
.set_identity(id.clone().as_bytes()) | ||
.expect("Failed to set identity"); | ||
socket.connect(addr).expect("Failed to connect to server"); | ||
info!("Connected to: {}", addr); | ||
loop { | ||
let rand_num = to_string(generate_random_number()); | ||
|
||
info!("{} connected to: {}", id, addr); | ||
loop { | ||
let rand_num = generate_random_number(); | ||
let rand_num_bytes = rand_num.to_le_bytes().to_vec(); | ||
// Send the message to the server | ||
match socket.send(rand_num.as_bytes(), 0) { | ||
Ok(_) => { | ||
info!("SND: fib({})=?", rand_num.clone()); | ||
} | ||
Err(snd_err) => { | ||
error!("SND: failed to send message: {:?}", snd_err); | ||
continue; | ||
} | ||
} | ||
|
||
match socket.send_multipart(vec![rand_num_bytes], 0) { | ||
Ok(_) => info!("{}, sent number: {}", id, rand_num), | ||
Err(snd_err) => { | ||
error!("{}, failed to send message: {:?}", id, snd_err); | ||
continue; | ||
} | ||
} | ||
// Receive the response from the server | ||
match socket.recv_multipart(0) { | ||
Ok(message) => { | ||
for (_, frame) in message.iter().enumerate() { | ||
match String::from_utf8(frame.clone()) { | ||
Ok(str_frame) => { | ||
if str_frame.is_empty() { | ||
continue; | ||
} | ||
|
||
match socket.recv_multipart(0) { | ||
Ok(message) => { | ||
info!("Client {}, received result: {:?}", client_id, message); | ||
} | ||
Err(rcv_err) => { | ||
error!( | ||
"Client {}, failed to receive message: {:?}", | ||
client_id, rcv_err | ||
); | ||
info!("RCV: fib({})={}", rand_num, str_frame); | ||
info!("--------------------------------------------------") | ||
} | ||
Err(e) => { | ||
error!("RCV: failed to convert frame to string: {:?}", e); | ||
} | ||
} | ||
} | ||
|
||
std::thread::sleep(std::time::Duration::from_millis(100)); | ||
} | ||
}); | ||
handles.push(handle); | ||
} | ||
|
||
loop { | ||
std::thread::sleep(std::time::Duration::from_secs(1)); | ||
Err(rcv_err) => { | ||
error!("RCV: failed to receive message: {:?}", rcv_err); | ||
} | ||
} | ||
} | ||
} | ||
|
||
fn generate_random_number() -> u8 { | ||
fn generate_random_number() -> u64 { | ||
let mut rng = rand::thread_rng(); | ||
rng.gen_range(0..=30) | ||
rng.gen_range(1..=80) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
use std::num::ParseIntError; | ||
|
||
#[derive(Debug)] | ||
pub enum NumberConversionError { | ||
InvalidLength(String), | ||
} | ||
|
||
// Converts a `u64` number to a `Vec<u8>` byte representation. | ||
pub fn to_bytes(num: u64) -> Vec<u8> { | ||
num.to_le_bytes().to_vec() | ||
} | ||
|
||
// Converts a `Vec<u8>` to a `u64` number. | ||
pub fn from_bytes(bytes: &[u8]) -> Result<u64, NumberConversionError> { | ||
match bytes.len() { | ||
8 => Ok(u64::from_le_bytes(bytes.try_into().map_err(|_| { | ||
NumberConversionError::InvalidLength(format!( | ||
"Invalid payload length: expected 8 bytes, got {}", | ||
bytes.len() | ||
)) | ||
})?)), | ||
_ => Err(NumberConversionError::InvalidLength(format!( | ||
"Invalid payload length: expected 8 bytes, got {}", | ||
bytes.len() | ||
))), | ||
} | ||
} | ||
|
||
pub fn to_string(num: u64) -> String { | ||
num.to_string() | ||
} | ||
|
||
pub fn from_string(num: &str) -> Result<u64, ParseIntError> { | ||
u64::from_str_radix(num, 16) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn test_to_bytes() { | ||
let num: u64 = 42; | ||
let bytes = to_bytes(num); | ||
assert_eq!(bytes, num.to_le_bytes().to_vec()); | ||
} | ||
|
||
#[test] | ||
fn test_from_bytes() { | ||
let num: u64 = 42; | ||
let bytes = num.to_le_bytes().to_vec(); | ||
let result = from_bytes(&bytes); | ||
assert_eq!(result.unwrap(), num); | ||
} | ||
|
||
#[test] | ||
fn test_invalid_length() { | ||
let bytes = vec![1, 2, 3]; // Length is not 8 bytes for a u64 number | ||
let result = from_bytes(&bytes); | ||
assert!(result.is_err()); | ||
} | ||
} |
Oops, something went wrong.