您现在的位置是:首页 > 文章详情

Deno 开源 fastwebsockets,Rust 编写的高性能 WebSocket 协议实现

日期:2023-05-03点击:581

Deno 开源了宣称速度极快的 fastwebsockets —— Rust 编写的高性能 WebSocket 协议 (RFC6455 WebSocket) 实现。

fastwebsockets 核心特性

  • 可用作原生 WebSocket 帧解析器、成熟的客户端/服务器
 use fastwebsockets::{Frame, OpCode, WebSocket}; async fn handle_client( mut socket: TcpStream, ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { handshake(&mut socket).await?; let mut ws = WebSocket::after_handshake(socket); ws.set_writev(true); ws.set_auto_close(true); ws.set_auto_pong(true); loop { let frame = ws.read_frame().await?; match frame { OpCode::Close => break, OpCode::Text | OpCode::Binary => { let frame = Frame::new(true, frame.opcode, None, frame.payload); ws.write_frame(frame).await?; } } } Ok(()) }
  • 与 Hyper 集成

启用upgrade功能以进行服务器端升级,以及与客户端握手。

 use fastwebsockets::upgrade::upgrade; use hyper::{Request, Body, Response}; async fn server_upgrade( mut req: Request<Body>, ) -> Result<Response<Body>, Box<dyn std::error::Error + Send + Sync>> { let (response, fut) = upgrade::upgrade(&mut req)?; tokio::spawn(async move { if let Err(e) = handle_client(fut).await { eprintln!("Error in websocket connection: {}", e); } }); Ok(response) }

使用 handshake 模块进行客户端握手:

 use fastwebsockets::handshake; use fastwebsockets::WebSocket; use hyper::{Request, Body, upgrade::Upgraded, header::{UPGRADE, CONNECTION}}; use tokio::net::TcpStream; use std::future::Future; // Define a type alias for convenience type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; async fn connect() -> Result<WebSocket<Upgraded>> { let stream = TcpStream::connect("localhost:9001").await?; let req = Request::builder() .method("GET") .uri("http://localhost:9001/") .header("Host", "localhost:9001") .header(UPGRADE, "websocket") .header(CONNECTION, "upgrade") .header( "Sec-WebSocket-Key", fastwebsockets:🤝:generate_key(), ) .header("Sec-WebSocket-Version", "13") .body(Body::empty())?; let (ws, _) = handshake::client(&SpawnExecutor, req, stream).await?; Ok(ws) } // Tie hyper's executor to tokio runtime struct SpawnExecutor; impl<Fut> hyper::rt::Executor<Fut> for SpawnExecutor where Fut: Future + Send + 'static, Fut::Output: Send + 'static, { fn execute(&self, fut: Fut) { tokio::task::spawn(fut); } }
  • 通过 Autobahn|TestSuite1 并使用 LLVM 的 libfuzzer 进行模糊测试
原文链接:https://www.oschina.net/news/239282/deno-fastwebsockets
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章