two-way file system sync
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

websocket.rs 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. use async_tungstenite::tungstenite::{Error as WsError, Message};
  2. use async_tungstenite::WebSocketStream;
  3. use futures::prelude::*;
  4. use futures::sink::Sink;
  5. use futures::stream::Stream;
  6. use futures::task::Context;
  7. use futures::task::Poll;
  8. use std::pin::Pin;
  9. pub struct WebSocketConnection<S> {
  10. stream: Pin<Box<WebSocketStream<S>>>,
  11. }
  12. impl<S> WebSocketConnection<S> {
  13. pub fn new(s: WebSocketStream<S>) -> Self {
  14. Self {
  15. stream: Box::pin(s),
  16. }
  17. }
  18. }
  19. impl<S> Sink<Vec<u8>> for WebSocketConnection<S>
  20. where
  21. S: AsyncRead + AsyncWrite + Unpin,
  22. {
  23. type Error = WsError;
  24. fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
  25. // Safe, as we will not move self_.
  26. let self_ = unsafe { self.get_unchecked_mut() };
  27. Pin::as_mut(&mut self_.stream).poll_ready(cx)
  28. }
  29. fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> {
  30. // Safe, as we will not move self_.
  31. let self_ = unsafe { self.get_unchecked_mut() };
  32. Pin::as_mut(&mut self_.stream).start_send(Message::Binary(item))
  33. }
  34. fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
  35. // Safe, as we will not move self_.
  36. let self_ = unsafe { self.get_unchecked_mut() };
  37. Pin::as_mut(&mut self_.stream).poll_flush(cx)
  38. }
  39. fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
  40. // Safe, as we will not move self_.
  41. let self_ = unsafe { self.get_unchecked_mut() };
  42. Pin::as_mut(&mut self_.stream).poll_close(cx)
  43. }
  44. }
  45. impl<S> Stream for WebSocketConnection<S>
  46. where
  47. S: AsyncRead + AsyncWrite + Unpin,
  48. {
  49. type Item = Result<Vec<u8>, WsError>;
  50. fn poll_next(
  51. self: Pin<&mut Self>,
  52. cx: &mut Context,
  53. ) -> Poll<Option<<WebSocketConnection<S> as Stream>::Item>> {
  54. // Safe, as we will not move self_.
  55. let self_ = unsafe { self.get_unchecked_mut() };
  56. match Pin::as_mut(&mut self_.stream).poll_next(cx) {
  57. Poll::Ready(Some(Ok(Message::Binary(data)))) => Poll::Ready(Some(Ok(data))),
  58. Poll::Ready(Some(Ok(_))) => unsafe {
  59. // Ignore other message types, try again.
  60. Pin::new_unchecked(self_).poll_next(cx)
  61. },
  62. Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
  63. Poll::Ready(None) => Poll::Ready(None),
  64. Poll::Pending => Poll::Pending,
  65. }
  66. }
  67. }