學習用書:《python 網絡編程基礎》作者John Goerzen
第一部分底層網絡學習
Python提供了訪問底層操作系統Socket接口的全部方法,需要的時候這些接口可以提供靈活而強有力的功能。
(1)基本客戶端操作
在《python 網絡編程基礎》一書中,作者列出了一個簡單的Python客戶端程序,具體如下:
代碼如下:
import socket,sys
port =70
host=sys.argv[1]
filename=sys.argv[2]
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
s.sendall(filename+"/r/n")
while 1:
buf=s.recv(2048)
if not len(buf):
break
sys.stdout.write(buf)
該程序實現的是Gopher協議,實現從主機上請求相關文檔的功能。(Gopher是Internet上一個非常有名的信息查找系統,它將Internet上的文件組織成某種索引,很方便地將用戶從Internet的一處帶到另一處。在WWW出現之前,Gopher是Internet上最主要的信息檢索工具,Gopher站點也是最主要的站點。但在WWW出現后,Gopher失去了昔日的輝煌?,F在它基本很少被使用。)
于是,我按照書上的語句進行了一下測試,在dos下運行python gopherclient.py quux.org。但是系統提示為
Traceback (most recent call last):
File "gopherclient.py", line 5, i
filename=sys.argv[2]
IndexError: list index out of range
看了一下,sys.argv只有兩個元素['gopherclient.py', 'quux.org/']所以filename=sys.argv[2]就超出下界了。可是為什么會出現這個原因呢?是書里面寫錯了嗎,因為我也是初學socket,不是很了解,所以我也是沒有找到原因,如果哪位大牛知道是什么原因,希望能給講解一下。
(2)基本服務器操作
《python 網絡編程基礎》一書中同樣給出了一個簡單的服務器程序,具體如下:
代碼如下:
import socket
host=''
port=51423
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)
print "Server is running on port %d;press Ctrl-C to terminate." %port
while 1:
clientsock,clientaddr=s.accept()
clientfile=clientsock.makefile('rw',0)
clientfile.write("welcome,"+str(clientaddr)+'/n')
clientfile.write("Please enter a string:")
line=clientfile.readline().strip()
clientfile.write("You entered %d characters./n" %len(line))
clientfile.close()
clientsock.close()
該程序運行后,提示“Server is running on port 51423:press Ctrl-C to terminate”。此時,通過另一臺機器telnet本機器的51423端口,如telnet 127.0.0.1:51423,此時會提示welcome 127.0.0.1 ****,please enter a string:。 然后輸入幾個字符后,會返回你輸入字符的個數。
新聞熱點
疑難解答