Skip to content

Commit

Permalink
Add flush method to ensure frame is correctly written (#88)
Browse files Browse the repository at this point in the history
When the underlying stream is buffered (i.e: TlsStream<TcpStream>)
calling write_frame is not enough to be guaranteed that data is pushed
down to the last stream (i.e: on the network in case of
TlsStream<TcpStream>).

Currently there is no way to force flush the data on the stream, so
write_frame call may never push the data.
https://docs.rs/tokio-rustls/latest/tokio_rustls/index.html#why-do-i-need-to-call-poll_flush

The commit introduce a flush method, to allow the user of the lib to
ensure all data is correctly pushed down.
  • Loading branch information
erebe authored Jan 4, 2025
1 parent e912a92 commit 4f274f4
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,21 @@ impl<'f, S> WebSocketWrite<S> {
{
self.write_half.write_frame(&mut self.stream, frame).await
}

pub async fn flush(&mut self) -> Result<(), WebSocketError>
where
S: AsyncWrite + Unpin,
{
flush(&mut self.stream).await
}
}

#[inline]
async fn flush<S>(stream: &mut S) -> Result<(), WebSocketError>
where
S: AsyncWrite + Unpin,
{
stream.flush().await.map_err(|e| WebSocketError::IoError(e))
}

/// WebSocket protocol implementation over an async stream.
Expand Down Expand Up @@ -495,6 +510,18 @@ impl<'f, S> WebSocket<S> {
Ok(())
}

/// Flushes the data from the underlying stream.
///
/// if the underlying stream is buffered (i.e: TlsStream<TcpStream>), it is needed to call flush
/// to be sure that the written frame are correctly pushed down to the bottom stream/channel.
///
pub async fn flush(&mut self) -> Result<(), WebSocketError>
where
S: AsyncWrite + Unpin,
{
flush(&mut self.stream).await
}

/// Reads a frame from the stream.
///
/// This method will unmask the frame payload. For fragmented frames, use `FragmentCollector::read_frame`.
Expand Down

0 comments on commit 4f274f4

Please sign in to comment.