0

I'm trying to make an asynchronous WebSocket server (my own implementation). I have the following code:

use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            let mut buffer = [0u8; 512];
            let stuff = match socket.read(&mut buffer).await {
                Ok(n) => buffer[..n].to_vec(),
                Err(_) => return,
            };
        });
    }
}

Now what do I do? According to the spec, I have to check the FIN bit, opcode, etc. but how do I do that. The FIN bit is just 1 bit, how are we supposed to get that out of a u8 array? Examples would help greatly.

  • 2
    To be clear, is your question just about how to read the first bit of a `u8` array? If so, there is a lot of noise in your question, related to Websocket specifics, which is not relevant if you just need to know how to read the bit. – Peter Hall Mar 25 '20 at 09:17
  • @PeterHall Yeah, I just thought there was this lingering possibility that I interpreted the specification incorrectly. I'll edit the question – MOHAMED ALSAN ALI Mar 25 '20 at 09:58
  • 2
    Your interpretation of [the spec](https://tools.ietf.org/html/rfc6455#section-5.2) seems correct. – Peter Hall Mar 25 '20 at 10:00

1 Answers1

1

To read the first bit from a byte buffer, you could use something like this:

fn fin_bit(buffer: &[u8]) -> Option<bool> {
    buffer.get(0)
        .map(|first_byte| first_byte & 0b10000000 > 0)
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204