1efbfdb0cSShuo Chen#pragma once 2efbfdb0cSShuo Chen#include "Common.h" 324ca08a8SShuo Chen#include "InetAddress.h" 4efbfdb0cSShuo Chen#include "Socket.h" 5efbfdb0cSShuo Chen 6efbfdb0cSShuo Chen#include <memory> 7efbfdb0cSShuo Chen 8efbfdb0cSShuo Chenclass TcpStream; 9efbfdb0cSShuo Chentypedef std::unique_ptr<TcpStream> TcpStreamPtr; 10efbfdb0cSShuo Chen 11efbfdb0cSShuo Chen// A blocking TCP stream 12efbfdb0cSShuo Chenclass TcpStream : noncopyable 13efbfdb0cSShuo Chen{ 14efbfdb0cSShuo Chen public: 15efbfdb0cSShuo Chen explicit TcpStream(Socket&& sock); // sock must be connected 16efbfdb0cSShuo Chen ~TcpStream() = default; 17efbfdb0cSShuo Chen TcpStream(TcpStream&&) = default; 188d51ab70SShuo Chen // TcpStream& operator=(TcpStream&&) = default; 19efbfdb0cSShuo Chen 20efbfdb0cSShuo Chen static TcpStreamPtr connect(const InetAddress& serverAddr); 21efbfdb0cSShuo Chen static TcpStreamPtr connect(const InetAddress& serverAddr, const InetAddress& localAddr); 22efbfdb0cSShuo Chen 23efbfdb0cSShuo Chen // NOT thread safe 24aafef3ccSShuo Chen int receiveAll(void* buf, int len); // read len bytes, unless error happens 25aafef3ccSShuo Chen int receiveSome(void* buf, int len); // read len or less bytes 26355c2bf7SShuo Chen 27efbfdb0cSShuo Chen int sendAll(const void* buf, int len); // send len bytes, unless error happens 28efbfdb0cSShuo Chen int sendSome(const void* buf, int len); // send len or less bytes 29efbfdb0cSShuo Chen 30355c2bf7SShuo Chen // thread safe 3124ca08a8SShuo Chen InetAddress getLocalAddr() const { return sock_.getLocalAddr(); } 3224ca08a8SShuo Chen InetAddress getPeerAddr() const { return sock_.getPeerAddr(); } 3324ca08a8SShuo Chen 34569528b0SShuo Chen void setTcpNoDelay(bool on); 35a52ee0fdSShuo Chen void shutdownWrite(); 36355c2bf7SShuo Chen 3714ca1249SShuo Chen int fd() { return sock_.fd(); } 3814ca1249SShuo Chen 39efbfdb0cSShuo Chen private: 40f41285cfSShuo Chen static TcpStreamPtr connectInternal(const InetAddress& serverAddr, const InetAddress* localAddr); 41efbfdb0cSShuo Chen Socket sock_; 42efbfdb0cSShuo Chen}; 43efbfdb0cSShuo Chen 44