voidget_URL(const string &host, const string &path){ // Your code here.
// You will need to connect to the "http" service on // the computer whose name is in the "host" string, // then request the URL path given in the "path" string.
// Then you'll need to print out everything the server sends back, // (not just one call to read() -- everything) until you reach // the "eof" (end of file). Address addr(host, "http"); TCPSocket st; st.connect(addr); st.write("GET " + path + " HTTP/1.1\r\n"); st.write("HOST: " + host + "\r\n"); st.write("Connection: close\r\n"); st.write("\r\n"); while(!st.eof()) { cout << st.read(); } st.close();
cerr << "Function called: get_URL(" << host << ", " << path << ").\n"; cerr << "Warning: get_URL() has not been implemented yet.\n"; }
byte_stream
需要实现一个可靠byte流。
大致需求:
需要限制缓冲区长度,在缓冲区未满时才能写入缓冲区
字节流可以无限长
它是单线程的,不用考虑并发
无非就是维护一个bytestream数据结构。
1 2 3 4 5 6 7 8 9 10
classByteStream { private: std::string _buffer; size_t _capacity = 0; size_t _read_count = 0; size_t _write_count = 0; bool _input_end_flag = false; bool _error = false; //!< Flag indicating that the stream suffered an error. ...
size_tByteStream::write(const string &data){ size_t cc = 0; for (size_t i = 0; i < data.size() && remaining_capacity() > 0; ++i, ++_write_count, ++cc) _buffer.push_back(data[i]);
return cc; }
//! \param[in] len bytes will be copied from the output side of the buffer string ByteStream::peek_output(constsize_t len)const{ return _buffer.substr(0, len); }
//! \param[in] len bytes will be removed from the output side of the buffer voidByteStream::pop_output(constsize_t len){ if (len >= buffer_size()) { _read_count += buffer_size(); _buffer.clear(); } else { _read_count += len; _buffer.erase(0, len); } }
//! Read (i.e., copy and then pop) the next "len" bytes of the stream //! \param[in] len bytes will be popped and returned //! \returns a string std::string ByteStream::read(constsize_t len){ string data = this->peek_output(len); this->pop_output(len); return data; }