#sockets #file-descriptor #web #rfc-6455

websocket-stream

非阻塞WebSocket (RFC-6455) 对TcpStream的包装

5个版本

使用旧的Rust 2015

0.0.5 2015年11月5日
0.0.4 2015年4月4日
0.0.3 2015年4月1日
0.0.2 2015年3月3日
0.0.1 2015年3月3日

#207 in WebSocket

MIT 许可证

35KB
623 代码行

websocket-stream

websocket-stream 是POSIX-like内核上TcpStreamRFC-6455包装器。它可以用于阻塞或非阻塞模式。

我没有足够的Windows开发经验来关心确保它是平台无关的。如果您想花时间实现Windows套接字,请随时向我发送pull request。

它通过在流的文件描述符上设置O_NONBLOCK标志来实现非阻塞状态。

示例用法

extern crate websocket_stream as wss;

use wss::{WebsocketStream, ReadResult, WriteResult, Mode};
use wss::util::{OpCode, ReadError, WriteError};

fn some_function() {
    // stream is some std::net::TcpStream
    let mut ws_stream = match WebsocketStream::new(stream, Mode::NonBlock) {
        Ok(ws) => ws,
        Err(e) => {
            // This arm is hit when the system does not support 0_NONBLOCK
            panic!("Websocket creation failed, errno: {}", e)
        }
    };

    // Read a thing
    match ws_stream.read() {
        Ok(res_tuple) => {
            match res_tuple.0 {
                OpCode::Continuation    => handle_cont(res_tuple.1),
                OpCode::Text            => handle_text(res_tuple.1),
                OpCode::Binary          => handle_binary(res_tuple.1),
                OpCode::Close           => handle_close(res_tuple.1),
                OpCode::Ping            => handle_ping(res_tuple.1),
                OpCode::Pong            => handle_pong(res_tuple.1)
            }
        }
        Err(e) => {
            match e {
                ReadError::EAGAIN => {
                    // This arm is hit in Mode::NonBlock
                    // Signifies there was no data to read
                }
                _ => {
                    // This arm is hit on syscall level errors.
                    // ReadError can be printed for details
                }
            }
        }
    }

    // Write a thing
    let mut buf: Vec<u8> = Vec::new(); // Buffer full of awesome
    match ws_stream.write(OpCode::Text, &mut buf) {
        Ok(num_written) => {
            // Obv, num_written is the amount of bytes written
        }
        Err(e) => {
            // This arm is hit on syscall level errors.
            // WriteError can be printed for details
        }
    }
}

依赖项

~0–7MB
~41K SLoC