1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 #include "pw_stream/socket_stream.h"
16 namespace pw::stream {
18 static constexpr uint32_t kMaxConcurrentUser = 1;
20 // Listen to the port and return after a client is connected
21 Status SocketStream::Init(uint16_t port) {
23 socket_fd_ = socket(AF_INET, SOCK_STREAM, 0);
24 if (socket_fd_ == kInvalidFd) {
25 return Status::Internal();
28 struct sockaddr_in addr;
29 addr.sin_family = AF_INET;
30 addr.sin_port = htons(listen_port_);
31 addr.sin_addr.s_addr = INADDR_ANY;
34 bind(socket_fd_, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr));
36 return Status::Internal();
39 result = listen(socket_fd_, kMaxConcurrentUser);
41 return Status::Internal();
44 socklen_t len = sizeof(sockaddr_client_);
47 accept(socket_fd_, reinterpret_cast<sockaddr*>(&sockaddr_client_), &len);
49 return Status::Internal();
54 Status SocketStream::DoWrite(std::span<const std::byte> data) {
55 ssize_t bytes_sent = send(conn_fd_, data.data(), data.size_bytes(), 0);
57 if (bytes_sent < 0 || static_cast<uint64_t>(bytes_sent) != data.size()) {
58 return Status::Internal();
63 StatusWithSize SocketStream::DoRead(ByteSpan dest) {
64 ssize_t bytes_rcvd = recv(conn_fd_, dest.data(), dest.size_bytes(), 0);
66 return StatusWithSize::Internal();
68 return StatusWithSize(bytes_rcvd);
71 }; // namespace pw::stream