Fix Old Websocket Server

Hi I was wondering if someone could help me update this old websocket code that I found. It seems to be promising as it has a way to keep track of a list of clients and a way to send a message to that list. However I'm facing some errors that likely would not have existed in the old version, and I'm not aware of the dependencies used. I'm not exactly skilled enough to get rid of errors without it affecting its original function so I would appreciate any help people can give me. This is the code in question:

use actix::*;
use actix_files as fs;
use actix_web::{App, HttpRequest, HttpServer};
use actix_web_actors::ws;
use std::sync::Mutex;

struct ChatState
{
    pub clients: Mutex<Vec<Addr<Ws>>>
}

struct Ws;

impl Actor for Ws
{
    type Context = ws::WebsocketContext<Self, ChatState>;
}

impl StreamHandler<ws::Message, ws::ProtocolError> for Ws
{
    fn started(&mut self, ctx: &mut Self::Context)
    {
        let mut clients = ctx.state().clients.lock().unwrap();

        clients.push(ctx.address());
    }

    fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context)
    {
        match msg
        {
            ws::Message::Ping(msg) => ctx.pong(&msg),
            ws::Message::Text(text) =>
            {
                for client in ctx.state().clients.lock().unwrap().iter()
                {
                    ctx.text(text);
                };
            },
            ws::Message::Binary(bin) => ctx.binary(bin),
            _ => ()
        }
    }
}

fn index(_req: &HttpRequest<ChatState>) -> actix_web::Result<fs::NamedFile>
{
    Ok(fs::NamedFile::open("index.html")?)
}

fn main()
{
    HttpServer::new(||
    {
        let state = ChatState { clients: Mutex::new(vec![]) };
        App::with_state(state)
        .resource("/", |r| r.f(index))
        .resource("/ws/", |r| r.f(|req| ws::start(req, Ws)))
    })
    .bind("localhost:8000").unwrap()
    .run();
}

And this is the current list of dependencies that I'm using:

actix = "0.10.0"
actix-files = "0.3.0"
actix-web = "3.0.0"
actix-web-actors = "3.0.0"
actix-rt = "1.0"

Thanks in advance!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.