Struct worker_plus::WebSocket
source · pub struct WebSocket { /* private fields */ }
Expand description
Wrapper struct for underlying worker-sys WebSocket
Implementations§
source§impl WebSocket
impl WebSocket
sourcepub async fn connect(url: Url) -> Result<WebSocket>
pub async fn connect(url: Url) -> Result<WebSocket>
Attempts to establish a WebSocket
connection to the provided Url
.
Example:
ⓘ
let ws = WebSocket::connect("wss://echo.zeb.workers.dev/".parse()?).await?;
// It's important that we call this before we send our first message, otherwise we will
// not have any event listeners on the socket to receive the echoed message.
let mut event_stream = ws.events()?;
ws.accept()?;
ws.send_with_str("Hello, world!")?;
while let Some(event) = event_stream.next().await {
let event = event?;
if let WebsocketEvent::Message(msg) = event {
if let Some(text) = msg.text() {
return Response::ok(text);
}
}
}
Response::error("never got a message echoed back :(", 500)
sourcepub fn accept(&self) -> Result<()>
pub fn accept(&self) -> Result<()>
Accepts the connection, allowing for messages to be sent to and from the WebSocket
.
sourcepub fn send<T: Serialize>(&self, data: &T) -> Result<()>
pub fn send<T: Serialize>(&self, data: &T) -> Result<()>
Serialize data into a string using serde and send it through the WebSocket
sourcepub fn send_with_str<S: AsRef<str>>(&self, data: S) -> Result<()>
pub fn send_with_str<S: AsRef<str>>(&self, data: S) -> Result<()>
Sends a raw string through the WebSocket
sourcepub fn send_with_bytes<D: AsRef<[u8]>>(&self, bytes: D) -> Result<()>
pub fn send_with_bytes<D: AsRef<[u8]>>(&self, bytes: D) -> Result<()>
Sends raw binary data through the WebSocket
.
sourcepub fn close<S: AsRef<str>>(
&self,
code: Option<u16>,
reason: Option<S>
) -> Result<()>
pub fn close<S: AsRef<str>>(
&self,
code: Option<u16>,
reason: Option<S>
) -> Result<()>
Closes this channel. This method translates to three different underlying method calls based of the parameters passed.
If the following parameters are Some:
code
andreason
->close_with_code_and_reason
code
->close_with_code
reason
ornone
->close
Effectively, if only reason
is Some
, the reason
argument will be ignored.
sourcepub fn events(&self) -> Result<EventStream<'_>>
pub fn events(&self) -> Result<EventStream<'_>>
Gets an implementation Stream
that yields events from the inner
WebSocket.