From e7380e5da83527b80087e86b63224e052074d10f Mon Sep 17 00:00:00 2001 From: Ronan Chauvin Date: Mon, 6 Jan 2025 12:58:56 -0800 Subject: [PATCH] pw_stream: Add ready method to socket stream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For now the connection is not ready when: * Read returned a wrong value (0 bytes = remote peer closed the connection). Close() is called. * Manually released or closed Change-Id: I9306116f01233a48e5d61e8054e0047ffce19b7c Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/253772 Pigweed-Auto-Submit: Armando Montanez Docs-Not-Needed: Ronan Chauvin Reviewed-by: Armando Montanez Lint: Lint 🤖 Reviewed-by: Ted Pudlik Commit-Queue: Ted Pudlik --- pw_stream/public/pw_stream/socket_stream.h | 3 +++ pw_stream/socket_stream.cc | 5 +++++ pw_stream/socket_stream_test.cc | 2 ++ 3 files changed, 10 insertions(+) diff --git a/pw_stream/public/pw_stream/socket_stream.h b/pw_stream/public/pw_stream/socket_stream.h index 6b6bd6a774..ec65ddf917 100644 --- a/pw_stream/public/pw_stream/socket_stream.h +++ b/pw_stream/public/pw_stream/socket_stream.h @@ -55,6 +55,9 @@ class SocketStream : public NonSeekableReaderWriter { const void* optval, unsigned int optlen); + // Get the connection ready state (true if ready, false otherwise). + bool IsReady(); + // Close the socket stream and release all resources void Close(); diff --git a/pw_stream/socket_stream.cc b/pw_stream/socket_stream.cc index d7cec21f08..baf0d66d39 100644 --- a/pw_stream/socket_stream.cc +++ b/pw_stream/socket_stream.cc @@ -162,6 +162,11 @@ int SocketStream::SetSockOpt(int level, return setsockopt(ownership.fd(), level, optname, optval, optlen); } +bool SocketStream::IsReady() { + std::lock_guard lock(connection_mutex_); + return ready_; +} + void SocketStream::Close() { ConnectionOwnership ownership(this); { diff --git a/pw_stream/socket_stream_test.cc b/pw_stream/socket_stream_test.cc index 3d3f268062..19139ed424 100644 --- a/pw_stream/socket_stream_test.cc +++ b/pw_stream/socket_stream_test.cc @@ -70,6 +70,7 @@ TEST(SocketStreamTest, ConnectSpecificPort) { SocketStream client; EXPECT_EQ(client.Connect("localhost", server.port()), OkStatus()); + EXPECT_TRUE(client.IsReady()); accept_thread.join(); EXPECT_EQ(server_stream.status(), OkStatus()); @@ -77,6 +78,7 @@ TEST(SocketStreamTest, ConnectSpecificPort) { server_stream.value().Close(); server.Close(); client.Close(); + EXPECT_FALSE(client.IsReady()); } // Helper function to test exchanging data on a pair of sockets.