Introduction
Set up
这里直接使用官方提供的虚拟机镜像:
https://stanford.edu/class/cs144/vm_howto/vm-howto-image.html
Networking by hand
使用 Telnet 访问 web
1 | cs144@cs144vm:~$ telnet cs144.keithw.org http |
由于没有 SUNet ID,所以跳过部分实验。104.196.238.229
Send yourself an email
同样还是跳过
Listening and connecting
使用netcat监听9000,并使用telnet访问。
1 | netcat -v -l -p 9000 |
Writing a network program using an OS stream socket
Let’s get started
代码 repo: https://github.com/cs144/sponge
可以考虑创建一个仓库,然后通过import的方式备份到自己的 GItHub 中,然后再 clone。
编译代码:
1 | mkdir build |
Modern C++
代码使用 Modern C++(>= C++11),Reference – CppCoreGuidelines
Basic idea:every object is designed to have the smallest possible public interface, has a lot of internal safety checks and is hard to use improperly, and knows how to clean up after itself.
- Never use
malloc()orfree() - Never use
newordelete - Essentially never use raw pointers,and user ‘smart’ pointers
unique_ptr,shared_ptr
- Avoid templates, threads, locks and virtual functions.
- Avoid C-style strings
- Never use C-style casts, and use
static_cast - Pefer passing function by
constreference - Make every variable
constunless it need to be mutated. - Make every method
constunless it need to mutate the object. - Avoid global variables.
make format
Reading the Sponge documentation
https://cs144.github.io/doc/lab0
- 从文档来看,
FileDescriptor好像只是把 Linux 下的文件描述符和一些文件操作封装成一个类了。 Socket是FileDescriptor的子类,加上了一些和 Socket 相关的API(抽象类)TCPScoekt是Socket的子类,添加了listen和acept等成员方法Adress是用来申明地址的,可以指定 IP 和端口
Writing webget
这个程序相当于是在代码中实现跑一边用telnect访问cs144.keithw.org的过程,所以建议复习一下lab0-networking-warmup#使用 Telnet 访问 web。
在文档里面也给了一些提示:
- 在网络中使用
\r\n而不是\n作为换行符 - 记得加上
Connection: close - 不要只使用一次
read(),而是需要用eof()来判断是否结束了
实现起来并不复杂,这里直接贴代码,唯一需要注意的就是最后有两个换行:
1 | void get_URL(const string &host, const string &path) { |
由于网络的问题,可能会导致在获取IP地址时花费大量时间,所以简易在/etc/hosts文件中配置好IP。例如:
1 | sduo echo "104.196.238.229 cs144.keithw.org" >> /etc/hosts |
测试:
1 | cs144@cs144vm:~/sponge/build$ make check_webget |
An in-memory reliable byte stream
这一部分是让我们实现一个内存中的字节流,主要有一下几点要求:
- 通过一个
capacity初始化,内存中 Buffer 的大小,当 Buffer 满了之后,限制写,直到有内容被读走了 - 不需要考虑并发问题
- the byte stream is finite, but it can be almost arbitrarily long4 before the writer ends the input and finishes the stream.
One More Thing
-