dev-resources.site
for different kinds of informations.
Websocket starter in Rust with client and server example
Published at
7/30/2024
Categories
rust
websocket
server
client
Author
campbellgoe
Author
11 person written this
campbellgoe
open
Server code for websockets
(server): https://github.com/campbellgoe/rust_websocket_server
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::protocol::Message;
use anyhow::Result;
use futures_util::{SinkExt, StreamExt};
#[tokio::main]
async fn main() -> Result<()> {
let addr = "127.0.0.1:8080".to_string();
let listener = TcpListener::bind(&addr).await?;
println!("WebSocket server started on ws://{}", addr);
while let Ok((stream, _)) = listener.accept().await {
tokio::spawn(handle_connection(stream));
}
Ok(())
}
async fn handle_connection(stream: tokio::net::TcpStream) -> Result<()> {
let mut ws_stream = accept_async(stream).await?;
println!("WebSocket connection established");
while let Some(msg) = ws_stream.next().await {
let msg = msg?;
if msg.is_text() {
let received_text = msg.to_text()?;
println!("Received message: {}", received_text);
ws_stream.send(Message::Text(received_text.to_string())).await?;
}
}
Ok(())
}
Cargo.toml (server):
[dependencies]
tokio = { version = "1.12", features = ["full"] }
tokio-stream = "0.1"
tokio-tungstenite = "0.23.1"
anyhow = "1.0"
futures-util = "0.3"
Client websocket code
(client): https://github.com/campbellgoe/rust_websocket_client
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::protocol::Message;
use anyhow::Result;
use futures_util::{SinkExt, StreamExt};
use url::Url;
#[tokio::main]
async fn main() -> Result<()> {
let url = Url::parse("ws://127.0.0.1:8080")?;
let (mut ws_stream, _) = connect_async(url.as_str()).await.expect("Failed to connect");
println!("WebSocket client connected");
// Sending a message to the server
let message = "Hello, Server!";
ws_stream.send(Message::Text(message.into())).await?;
// Receiving messages from the server
while let Some(msg) = ws_stream.next().await {
match msg? {
Message::Text(text) => {
println!("Received message from server: {}", text);
}
_ => {}
}
}
Ok(())
}
client Cargo.toml
[dependencies]
tokio = { version = "1.12", features = ["full"] }
tokio-stream = "0.1"
tokio-tungstenite = "0.23.1"
url = "2"
anyhow = "1.0"
futures-util = "0.3"
You could use this as a starting point for your Rust websocket project.
client Article's
30 articles in total
How I 15x My Freelance Business in 2024 – and Transformed My Life Along the Way
read article
Postman vs Bruno REST API Client
read article
Client Boundaries
read article
Websocket starter in Rust with client and server example
currently reading
Fusion : The Notion Like API Client
read article
How to setup postgres on ubuntu 20.04
read article
S.E.O Services In Affordable Price (Discount)
read article
Generate API Clients: A new way to consume REST APIs and GraphQL
read article
Finding Clients as a (Web Development) Freelancer - Part 2
read article
Finding Clients as a (Web Development) Freelancer
read article
How I Lost My First Client? 3 Mistakes to Avoid
read article
How web technology works? - Part 01
read article
Exploring the Dynamics of Client-Server Architecture
read article
understand short polling with example
read article
Building a HTTP Client with Reqwest | Rust
read article
Fundamentals of Networking: Connecting the Digital World
read article
Elevating Client Relationships with Thoughtful Gift Boxes
read article
Proper Method for Storing User Data on the Client Side in React for Authentication
read article
The Postico 2 client for YugabyteDB
read article
7 Best MQTT Client Tools Worth Trying in 2023
read article
Configurando o Spring Boot Admin: Server e Client
read article
Http Client API in Java: Authentication
read article
A simple guide to Java http calls
read article
HTTP Methods In A Nutshell
read article
Retrieving, using and validating token from an IdentityServer
read article
Free Database Client For PostGresql
read article
Azure - Registering a client credentials app
read article
Multiple MySQL Router Client in Single Server/Nodes
read article
5 Awesome Python HTTP Clients
read article
5 Awesome JavaScript HTTP Clients
read article
Featured ones: