1#pragma once
2#include "Common.h"
3#include "InetAddress.h"
4#include "Socket.h"
5
6#include <memory>
7
8class TcpStream;
9typedef std::unique_ptr<TcpStream> TcpStreamPtr;
10
11// A blocking TCP stream
12class TcpStream : noncopyable
13{
14 public:
15  explicit TcpStream(Socket&& sock);  // sock must be connected
16  ~TcpStream() = default;
17  TcpStream(TcpStream&&) = default;
18  // TcpStream& operator=(TcpStream&&) = default;
19
20  static TcpStreamPtr connect(const InetAddress& serverAddr);
21  static TcpStreamPtr connect(const InetAddress& serverAddr, const InetAddress& localAddr);
22
23  // NOT thread safe
24  int receiveAll(void* buf, int len);  // read len bytes, unless error happens
25  int receiveSome(void* buf, int len); // read len or less bytes
26
27  int sendAll(const void* buf, int len);  // send len bytes, unless error happens
28  int sendSome(const void* buf, int len); // send len or less bytes
29
30  // thread safe
31  InetAddress getLocalAddr() const { return sock_.getLocalAddr(); }
32  InetAddress getPeerAddr() const { return sock_.getPeerAddr(); }
33
34  void setTcpNoDelay(bool on);
35  void shutdownWrite();
36
37  int fd() { return sock_.fd(); }
38
39 private:
40  static TcpStreamPtr connectInternal(const InetAddress& serverAddr, const InetAddress* localAddr);
41  Socket sock_;
42};
43
44