#details #protocols #low-level #websocket-client #url #header

已删除 裸WebSocket

仅WebSocket (RFC6455) 的简单客户端实现,暴露底层协议细节(如有需要)

使用旧的Rust 2015

0.0.6 2015年2月23日
0.0.5 2015年2月5日
0.0.1 2015年1月11日

#67 in #websocket-client

MIT 许可证

29KB
626 代码行

裸WebSocket

根据 RFC6455 在Rust中实现的WebSocket

与其他websocket库不同,这个库更专注于WebSocket协议的更底层细节:您可以单独检查每个帧,以及帧头。您可以逐位准备每个帧,以及所有头部细节。它还支持掩码、自定义(特定服务)操作码和保留位。

另一方面,它仅实现WebSocket客户端(但消息结构是通用的,可用于实现客户端和服务器部分)。

如果您不需要处理所有协议的恐怖细节,希望有更高级的接口和现成的WebSocket服务器实现,请使用websocket

要使用,请将依赖项添加到您的Cargo.toml中(您还需要url crate)

[dependencies]
url = "*"
bare-websocket = "*"

然后在您的代码中

extern crate url;
extern crate "bare-websocket" as websocket;

use websocket::{WebSocket, WSMessage};
use url::Url;

示例代码

// Initialization
let url = Url::parse("ws://echo.websocket.org").unwrap(); // <-- also supports SSL, just use "wss://" schema
let mut ws = WebSocket::new(url);
ws.connect().unwrap(); // <-- you can pass configured WebSocket somewhere before connecting

let msg = WSMessage::text("Hello, World!"); //.mask(); // <-- optionally turn on automasking
// All masking/unmasking is done transparently, you will never even know about it!

// You can compose fragmented messages as well:
let msg1 = WSMessage::text("Hello").first(); // <-- first fragment
let msg2 = WSMessage::text(", ").more(); // <-- continue fragment
let msg3 = WSMessage::text("world!").last(); // <-- last fragment

// Or easier: split message by size:
for m in WSMessage::text("Hello, world!").split(5) { // <-- WSMessage iterator
    ws.send_message(&m).unwrap();
}

// Usage of .defrag()menting iterator below (you can get each message fragment by not using it)
let reply = ws.iter().defrag().next().unwrap();
println!("received: {} {}", reply, reply.to_string());

// You can get single message as well:
//let msg = ws.read_message().unwrap();

// Simple messages iterator, to handle defragmentation, append .defrag() after .iter()
for msg in ws.iter() {
    println!("{}", msg.to_string());
}

// To take full bitwise control of opcode field, use `.ext()` method
let msg = WSMessage::ext(0b1011, b"bare metal message"); // <-- this is an extension control opcode

// There are also a lot of `.is_???()` methods to inspect:
println!("{}", msg.is_ext(0b1011)); // is it given extended opcode?
println!("{}", msg.is_control()); // is it control or data opcode?
println!("{}", msg.is_text()); // is it a text message?
println!("{}", msg.is_binary()); // is it a binary message?
// Also exist: .is_ping(), .is_pong(), .is_close(), .is_cont()

实际上就是这样。

依赖项

~3.5–5MB
~129K SLoC