TcpStream.h revision 8d51ab70
1efbfdb0cSShuo Chen#pragma once
2efbfdb0cSShuo Chen#include "Common.h"
3efbfdb0cSShuo Chen#include "Socket.h"
4efbfdb0cSShuo Chen
5efbfdb0cSShuo Chen#include <memory>
6efbfdb0cSShuo Chen
7efbfdb0cSShuo Chenclass InetAddress;
8efbfdb0cSShuo Chen
9efbfdb0cSShuo Chenclass TcpStream;
10efbfdb0cSShuo Chentypedef std::unique_ptr<TcpStream> TcpStreamPtr;
11efbfdb0cSShuo Chen
12efbfdb0cSShuo Chen// A blocking TCP stream
13efbfdb0cSShuo Chenclass TcpStream : noncopyable
14efbfdb0cSShuo Chen{
15efbfdb0cSShuo Chen public:
16efbfdb0cSShuo Chen  explicit TcpStream(Socket&& sock);  // sock must be connected
17efbfdb0cSShuo Chen  ~TcpStream() = default;
18efbfdb0cSShuo Chen  TcpStream(TcpStream&&) = default;
198d51ab70SShuo Chen  // TcpStream& operator=(TcpStream&&) = default;
20efbfdb0cSShuo Chen
21efbfdb0cSShuo Chen  static TcpStreamPtr connect(const InetAddress& serverAddr);
22efbfdb0cSShuo Chen  static TcpStreamPtr connect(const InetAddress& serverAddr, const InetAddress& localAddr);
23efbfdb0cSShuo Chen
24efbfdb0cSShuo Chen  // NOT thread safe
25aafef3ccSShuo Chen  int receiveAll(void* buf, int len);  // read len bytes, unless error happens
26aafef3ccSShuo Chen  int receiveSome(void* buf, int len); // read len or less bytes
27355c2bf7SShuo Chen
28efbfdb0cSShuo Chen  int sendAll(const void* buf, int len);  // send len bytes, unless error happens
29efbfdb0cSShuo Chen  int sendSome(const void* buf, int len); // send len or less bytes
30efbfdb0cSShuo Chen
31355c2bf7SShuo Chen  // thread safe
32569528b0SShuo Chen  void setTcpNoDelay(bool on);
33a52ee0fdSShuo Chen  void shutdownWrite();
34355c2bf7SShuo Chen
35efbfdb0cSShuo Chen private:
36f41285cfSShuo Chen  static TcpStreamPtr connectInternal(const InetAddress& serverAddr, const InetAddress* localAddr);
37efbfdb0cSShuo Chen  Socket sock_;
38efbfdb0cSShuo Chen};
39efbfdb0cSShuo Chen
40