Skip to content

Instantly share code, notes, and snippets.

@drojf
Created January 19, 2019 10:08
Show Gist options
  • Save drojf/d808ee37e50e4485b07f04e59cb2088e to your computer and use it in GitHub Desktop.
Save drojf/d808ee37e50e4485b07f04e59cb2088e to your computer and use it in GitHub Desktop.
//! Note that the terms "client" and "server" here are purely what we logically associate with them.
//! Technically, they both work the same.
//! Note that in practice you don't want to implement a chat client using UDP.
use std::io::stdin;
use laminar::{config::NetworkConfig, error::Result, net::UdpSocket, Packet};
const SERVER: &str = "127.0.0.1:12351";
fn server() -> Result<()> {
let mut socket = UdpSocket::bind(SERVER, NetworkConfig::default())?;
println!("Listening for connections to {}", SERVER);
loop {
match socket.recv()? {
Some(packet) => {
let msg = packet.payload();
if msg == b"Bye!" {
break;
}
let msg = String::from_utf8_lossy(msg);
let ip = packet.addr().ip();
println!("Received {:?} from {:?}", msg, ip);
socket.send(&Packet::reliable_unordered(
packet.addr(),
"Copy that!".as_bytes().to_vec(),
))?;
socket.send(&Packet::reliable_unordered(
packet.addr(),
"Copy that!".as_bytes().to_vec(),
))?;
}
None => {}
}
}
Ok(())
}
fn client() -> Result<()> {
let mut socket = UdpSocket::bind("127.0.0.1:12352", NetworkConfig::default())?;
let server = SERVER.parse()?;
println!("Type a message and press Enter to send. Send `Bye!` to quit.");
let stdin = stdin();
let mut s_buffer = String::new();
loop {
s_buffer.clear();
//stdin.read_line(&mut s_buffer)?;
let line = vec![1,2,3,41,2,3,41,2,3,41,2,3,41,2,3,41,2,3,4]; s_buffer.replace(|x| x == '\n' || x == '\r', "");
socket.send(&Packet::reliable_unordered(
server,
line.clone(),
))?;
socket.send(&Packet::reliable_unordered(
server,
line.clone(),
))?;
let back = socket.recv()?;
match back {
Some(packet) => {
if packet.addr() == server {
println!("Server sent: {}", String::from_utf8_lossy(packet.payload()));
} else {
println!("Unknown sender.");
}
}
None => {println!("Silence..");},
}
}
Ok(())
}
fn main() -> Result<()> {
let stdin = stdin();
println!("Please type in `server` or `client`.");
let mut s = String::new();
stdin.read_line(&mut s)?;
if s.starts_with("s") {
println!("Starting server..");
server()
} else {
println!("Starting client..");
client()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment