程序员

Network学习-第一次网路编程

2017-10-15  本文已影响0人  Yojiaku

Network学习-第一次网络编程实例

#!/usr/bin/env python
# Simple Gopher Client - Chapter 1 - gopherclient.py

import socket, sys

port = 70   # Gopher uses port 70
host = sys.argv[1]
filename = sys.argv[2]

s =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#调用socket.socket()建立一个Socket,参数告诉系统需要一个Internet socket来进行TCP通信
s.connect((host, port))
#程序连接远程主机

s.sendall(filename + "\r\n")
#并提供文件名

while 1:
    buf = s.recv(2048)
    if not len(buf):
        break
    sys.stdout.write(buf)
#最后,获得响应后,在屏幕上打印出来

将上述代码保存为"chapter1_gopherclient.py",然后在Linux下打开终端,切换到代码目录,敲下命令:

python ./chapter1_gopherclient.py quux.org /

注意不要忘记后面的“/”,与前面隔了一个空格
上述代码实现的是Gopher协议(一种Web出现之前在Internet上非常流行的协议),这个程序需要两个命令行参数:主机名和文件名,实现从主机上请求相关文档的功能。
如果程序正确,那么我们得到的结果将会是下面这样的:

iWelcome to gopher at quux.org! fake (NULL) 0
i fake (NULL) 0
iThis server has a lot of information of historic interest, fake (NULL) 0
……
1The Gopher Project /Software/Gopher gopher.quux.org 70
0What's New /whatsnew.txt gopher.quux.org 70 +

“诶?!居然没有错误检查”
实际上并不是这样,Python会自动进行错误检查,并在有错误发生时产生异常。例如,修改下上面的命令,给一个不存在的主机名,例如

python ./chapter1_gopherclient.py nonexistant.example.com /

就会收到一个socket.error异常(相关的文字和数字或许不同):

Traceback (most recent call last):
File "./chapter1_gopherclient.py", line 11, in <module>
s.connect((host, port))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 110] Connection timed out

第一次修改代码

修改程序让其显示一个友好的错误信息:

#!/usr/bin/env python
# Simple Gopher Client - Chapter 1 - gopherclient.py

import socket, sys

port = 70   # Gopher uses port 70
host = sys.argv[1]
filename = sys.argv[2]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((host, port))
except socket.error, e:
    print "Error connecting to server: %s" % e
    sys.exit(1)

s.sendall(filename + "\r\n")

while 1:
    buf = s.recv(2048)
    if not len(buf):
        break
    sys.stdout.write(buf)

此时,报错将会是这样的:

Error connecting to server: [Errno 110] Connection timed out

注意不要用中文,中文将无法识别

第二次修改代码

Python库支持文件和文件类对象,但是Socket对象不提供类似的接口,可以用makefile()函数来生成供我们使用的文件类对象,改写上面的代码使用文件类接口:

#!/usr/bin/env python
# Simple Gopher Client - Chapter 1 - gopherclient.py

import socket, sys

port = 70   # Gopher uses port 70
host = sys.argv[1]
filename = sys.argv[2]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((host, port))
except socket.error, e:
    print "Error connecting to server: %s" % e
    sys.exit(1)

'''
s.sendall(filename + "\r\n")

while 1:
   buf = s.recv(2048)
    if not len(buf):
        break
    sys.stdout.write(buf)
'''
# The following is the content of rewritting
fd = s.makefile('rw', 0) # call makefile()

fd.write(filename + "\r\n")

for line in fd.readlines():
    sys.stdout.write(line)

makefile()函数
makefile()函数有两个可选参数:操作文件类的模式和缓存(buffering)的模式。操作文件类的模式表明是只读、只写或是既读又写(这个例子为既读又写rw)。缓存主要用在磁盘文件,但是对于交互式的网络程序,它可能会阻碍程序的运行,所以最好通过设置为0来关闭这个功能。

上一篇下一篇

猜你喜欢

热点阅读