leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 비동기 스트림 위의 제어 프레임 송수신. |
| 2 | |
| 3 | use bytes::BytesMut; |
| 4 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; |
| 5 | |
| 6 | use crate::protocol::{Frame, FrameDecoder, Message, ProtocolError, encode_frame}; |
| 7 | |
| 8 | /// 제어 채널 송수신 중 오류. |
| 9 | #[derive(Debug)] |
| 10 | pub enum FramedError { |
| 11 | Io(std::io::Error), |
| 12 | Protocol(ProtocolError), |
| 13 | /// 상대가 연결을 닫았다. |
| 14 | Closed, |
| 15 | } |
| 16 | |
| 17 | impl std::fmt::Display for FramedError { |
| 18 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 19 | match self { |
| 20 | Self::Io(e) => write!(f, "입출력 오류: {e}"), |
| 21 | Self::Protocol(e) => write!(f, "프로토콜 오류: {e}"), |
| 22 | Self::Closed => f.write_str("상대가 연결을 닫았습니다"), |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl std::error::Error for FramedError {} |
| 28 | |
| 29 | impl From<std::io::Error> for FramedError { |
| 30 | fn from(e: std::io::Error) -> Self { |
| 31 | Self::Io(e) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | impl From<ProtocolError> for FramedError { |
| 36 | fn from(e: ProtocolError) -> Self { |
| 37 | Self::Protocol(e) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /// 제어 프레임 단위로 읽고 쓰는 스트림 래퍼. `S`는 보통 TLS 스트림이다. |
| 42 | pub struct FramedStream<S> { |
| 43 | stream: S, |
| 44 | decoder: FrameDecoder, |
| 45 | read_buf: Vec<u8>, |
| 46 | next_seq: u16, |
| 47 | } |
| 48 | |
| 49 | impl<S: AsyncRead + AsyncWrite + Unpin> FramedStream<S> { |
| 50 | pub fn new(stream: S) -> Self { |
| 51 | Self { |
| 52 | stream, |
| 53 | decoder: FrameDecoder::new(), |
| 54 | read_buf: vec![0; 16 * 1024], |
| 55 | next_seq: 0, |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// 완성된 프레임 하나를 읽는다. |
| 60 | pub async fn read_frame(&mut self) -> Result<Frame, FramedError> { |
| 61 | loop { |
| 62 | if let Some(frame) = self.decoder.decode()? { |
| 63 | return Ok(frame); |
| 64 | } |
| 65 | let n = self.stream.read(&mut self.read_buf).await?; |
| 66 | if n == 0 { |
| 67 | return Err(FramedError::Closed); |
| 68 | } |
| 69 | self.decoder.extend(&self.read_buf[..n]); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// 프레임을 읽어 메시지로 해석한다. seq_id도 함께 돌려준다. |
| 74 | pub async fn read_message(&mut self) -> Result<(u16, Message), FramedError> { |
| 75 | let frame = self.read_frame().await?; |
| 76 | let seq = frame.header.seq_id; |
| 77 | Ok((seq, Message::decode(&frame)?)) |
| 78 | } |
| 79 | |
| 80 | /// 다음 순환 seq_id로 메시지를 보낸다. 사용한 seq_id를 돌려준다. |
| 81 | pub async fn send(&mut self, msg: &Message) -> Result<u16, FramedError> { |
| 82 | let seq = self.next_seq; |
| 83 | self.next_seq = self.next_seq.wrapping_add(1); |
| 84 | self.send_with_seq(msg, seq).await?; |
| 85 | Ok(seq) |
| 86 | } |
| 87 | |
| 88 | /// 지정한 seq_id로 보낸다. PONG, ACK처럼 요청의 seq_id를 되돌려줄 때 쓴다. |
| 89 | pub async fn send_with_seq(&mut self, msg: &Message, seq: u16) -> Result<(), FramedError> { |
| 90 | let mut buf = BytesMut::new(); |
| 91 | encode_frame(&msg.to_frame(seq), &mut buf); |
| 92 | self.stream.write_all(&buf).await?; |
| 93 | self.stream.flush().await?; |
| 94 | Ok(()) |
| 95 | } |
| 96 | |
| 97 | pub fn get_ref(&self) -> &S { |
| 98 | &self.stream |
| 99 | } |
| 100 | |
| 101 | pub fn into_inner(self) -> S { |
| 102 | self.stream |
| 103 | } |
| 104 | } |