Logo

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
Categories
4 categories in total
rust
open
websocket
open
server
open
client
open
Author
11 person written this
campbellgoe
open
Websocket starter in Rust with client and server example

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(())
}
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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(())
}
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

You could use this as a starting point for your Rust websocket project.

client Article's
30 articles in total
Favicon
How I 15x My Freelance Business in 2024 – and Transformed My Life Along the Way
Favicon
Postman vs Bruno REST API Client
Favicon
Client Boundaries
Favicon
Websocket starter in Rust with client and server example
Favicon
Fusion : The Notion Like API Client
Favicon
How to setup postgres on ubuntu 20.04
Favicon
S.E.O Services In Affordable Price (Discount)
Favicon
Generate API Clients: A new way to consume REST APIs and GraphQL
Favicon
Finding Clients as a (Web Development) Freelancer - Part 2
Favicon
Finding Clients as a (Web Development) Freelancer
Favicon
How I Lost My First Client? 3 Mistakes to Avoid
Favicon
How web technology works? - Part 01
Favicon
Exploring the Dynamics of Client-Server Architecture
Favicon
understand short polling with example
Favicon
Building a HTTP Client with Reqwest | Rust
Favicon
Fundamentals of Networking: Connecting the Digital World
Favicon
Elevating Client Relationships with Thoughtful Gift Boxes
Favicon
Proper Method for Storing User Data on the Client Side in React for Authentication
Favicon
The Postico 2 client for YugabyteDB
Favicon
7 Best MQTT Client Tools Worth Trying in 2023
Favicon
Configurando o Spring Boot Admin: Server e Client
Favicon
Http Client API in Java: Authentication
Favicon
A simple guide to Java http calls
Favicon
HTTP Methods In A Nutshell
Favicon
Retrieving, using and validating token from an IdentityServer
Favicon
Free Database Client For PostGresql
Favicon
Azure - Registering a client credentials app
Favicon
Multiple MySQL Router Client in Single Server/Nodes
Favicon
5 Awesome Python HTTP Clients
Favicon
5 Awesome JavaScript HTTP Clients

Featured ones: