Hi, I'm trying to learn how to use websockets so I can create a real-time messaging system. I looked over the documentation for websockets on actix but I'm still a little confused on how to operate with it.
This is the referred to code which is a websocket echo server:
use actix::{Actor, StreamHandler};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
/// Define HTTP actor
struct MyWs;
impl Actor for MyWs {
type Context = ws::WebsocketContext<Self>;
}
/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
match msg {
Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
Ok(ws::Message::Text(text)) => ctx.text(text),
Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
_ => (),
}
}
}
async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
let resp = ws::start(MyWs {}, &req, stream);
println!("{:?}", resp);
resp
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/ws/", web::get().to(index)))
.bind("127.0.0.1:8080")?
.run()
.await
}
My question is how do I actually send a message for it to then be echoed back. I'm confused on how to trigger this from the clientside because obviously with only this I'm led to a 404/400 error since an html page isn't found at localhost:8080? I know some clientside html and javascript is needed, but I'd appreciate an example: do I need to send some kind of post or get request to the websocket server?
Thanks in advance!