This commit is contained in:
azw 2024-05-04 17:30:02 +08:00
parent 5e8780bbe9
commit 2c399e2d92

View File

@ -6,39 +6,44 @@ mod upstream;
mod downstream; mod downstream;
mod ss; mod ss;
use crate::app::UserApp; use crate::app::UserApp;
use actix_web::{web, App as ActixApp, get, post, Responder, HttpServer, HttpResponse}; use actix_web::{web, App as ActixApp, get, post, Responder, Error, HttpServer, HttpRequest, HttpResponse};
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;
use actix_rt::System; use actix_rt::System;
use std::time::Duration; use std::time::Duration;
use actix_web_actors::ws;
use actix::{Actor, StreamHandler};
async fn index() -> impl Responder { /// Define HTTP actor
"Hello world34444!" struct MyWs;
}
#[get("/")] impl Actor for MyWs {
async fn hello() -> impl Responder { type Context = ws::WebsocketContext<Self>;
HttpResponse::Ok().body("Hello world!")
} }
#[post("/echo")] /// Handler for ws::Message message
async fn echo(req_body: String) -> impl Responder { impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
HttpResponse::Ok().body(req_body) 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 manual_hello() -> impl Responder { async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
HttpResponse::Ok().body("Hey there!") let resp = ws::start(MyWs {}, &req, stream);
println!("{:?}", resp);
resp
} }
fn main() { fn main() {
let t1 = thread::spawn(||{ let t1 = thread::spawn(||{
let mut rt = tokio::runtime::Runtime::new().unwrap(); let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { rt.block_on(async {
HttpServer::new(|| { HttpServer::new(|| ActixApp::new().route("/ws/", web::get().to(index)))
ActixApp::new()
.service(hello)
.service(echo)
.route("/hey", web::get().to(manual_hello))
})
.bind(("127.0.0.1", 8080))? .bind(("127.0.0.1", 8080))?
.run() .run()
.await .await