Python 的 Socket 編程教程


這是用來快速學習 Python Socket 套接字編程的指南和教程。Python 的 Socket 編程跟 C 語言很像。

Python 官方關於 Socket 的函數請看 http://docs.python.org/library/socket.html

基本上,Socket 是任何一種計算機網絡通訊中最基礎的內容。例如當你在瀏覽器地址欄中輸入 www.oschina.net 時,你會打開一個套接字,然后連接到 www.oschina.net 並讀取響應的頁面然后然后顯示出來。而其他一些聊天客戶端如 gtalk 和 skype 也是類似。任何網絡通訊都是通過 Socket 來完成的。

寫在開頭

本教程假設你已經有一些基本的 Python 編程的知識。

讓我們開始 Socket 編程吧。

創建 Socket

首先要做的就是創建一個 Socket,socket 的 socket 函數可以實現,代碼如下:

1 #Socket client example in python
2  
3 import socket   #for sockets
4  
5 #create an AF_INET, STREAM socket (TCP)
6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
7  
8 print 'Socket Created'

函數 socket.socket 創建了一個 Socket,並返回 Socket 的描述符可用於其他 Socket 相關的函數。

上述代碼使用了下面兩個屬性來創建 Socket:

地址簇 : AF_INET (IPv4)
類型: SOCK_STREAM (使用 TCP 傳輸控制協議)

錯誤處理

如果 socket 函數失敗了,python 將拋出一個名為 socket.error 的異常,這個異常必須予以處理:

01 #handling errors in python socket programs
02  
03 import socket   #for sockets
04 import sys  #for exit
05  
06 try:
07     #create an AF_INET, STREAM socket (TCP)
08     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
09 except socket.error, msg:
10     print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
11     sys.exit();
12  
13 print 'Socket Created'

好了,假設你已經成功創建了 Socket,下一步該做什么呢?接下來我們將使用這個 Socket 來連接到服務器。

注意

與 SOCK_STREAM 相對應的其他類型是 SOCK_DGRAM 用於 UDP 通訊協議,UDP 通訊是非連接 Socket,在這篇文章中我們只討論 SOCK_STREAM ,或者叫 TCP 。

連接到服務器

連接到服務器需要服務器地址和端口號,這里使用的是 www.oschina.net 和 80 端口。

首先獲取遠程主機的 IP 地址

連接到遠程主機之前,我們需要知道它的 IP 地址,在 Python 中,獲取 IP 地址是很簡單的:

01 import socket   #for sockets
02 import sys  #for exit
03  
04 try:
05     #create an AF_INET, STREAM socket (TCP)
06     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
07 except socket.error, msg:
08     print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
09     sys.exit();
10  
11 print 'Socket Created'
12  
13 host = 'www.oschina.net'
14  
15 try:
16     remote_ip = socket.gethostbyname( host )
17  
18 except socket.gaierror:
19     #could not resolve
20     print 'Hostname could not be resolved. Exiting'
21     sys.exit()
22      
23 print 'Ip address of ' + host + ' is ' + remote_ip

我們已經有 IP 地址了,接下來需要指定要連接的端口。

代碼:

01 import socket   #for sockets
02 import sys  #for exit
03  
04 try:
05     #create an AF_INET, STREAM socket (TCP)
06     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
07 except socket.error, msg:
08     print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
09     sys.exit();
10  
11 print 'Socket Created'
12  
13 host = 'www.oschina.net'
14 port = 80
15  
16 try:
17     remote_ip = socket.gethostbyname( host )
18  
19 except socket.gaierror:
20     #could not resolve
21     print 'Hostname could not be resolved. Exiting'
22     sys.exit()
23      
24 print 'Ip address of ' + host + ' is ' + remote_ip
25  
26 #Connect to remote server
27 s.connect((remote_ip , port))
28  
29 print 'Socket Connected to ' + host + ' on ip ' + remote_ip

現在運行程序

1 $ python client.py
2 Socket Created
3 Ip address of www.oschina.net is 61.145.122.155
4 Socket Connected to www.oschina.net on ip 61.145.122.155

這段程序創建了一個 Socket 並進行連接,試試使用其他一些不存在的端口(如81)會是怎樣?這個邏輯相當於構建了一個端口掃描器。

已經連接上了,接下來就是往服務器上發送數據。

免費提示

使用 SOCK_STREAM/TCP 套接字才有“連接”的概念。連接意味着可靠的數據流通訊機制,可以同時有多個數據流。可以想象成一個數據互不干擾的管道。另外一個重要的提示是:數據包的發送和接收是有順序的。

其他一些 Socket 如 UDP、ICMP 和 ARP 沒有“連接”的概念,它們是無連接通訊,意味着你可從任何人或者給任何人發送和接收數據包。

發送數據

sendall 函數用於簡單的發送數據,我們來向 oschina 發送一些數據:

01 import socket   #for sockets
02 import sys  #for exit
03  
04 try:
05     #create an AF_INET, STREAM socket (TCP)
06     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
07 except socket.error, msg:
08     print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
09     sys.exit();
10  
11 print 'Socket Created'
12  
13 host = 'www.oschina.net'
14 port = 80
15  
16 try:
17     remote_ip = socket.gethostbyname( host )
18  
19 except socket.gaierror:
20     #could not resolve
21     print 'Hostname could not be resolved. Exiting'
22     sys.exit()
23      
24 print 'Ip address of ' + host + ' is ' + remote_ip
25  
26 #Connect to remote server
27 s.connect((remote_ip , port))
28  
29 print 'Socket Connected to ' + host + ' on ip ' + remote_ip
30  
31 #Send some data to remote server
32 message = "GET / HTTP/1.1\r\n\r\n"
33  
34 try :
35     #Set the whole string
36     s.sendall(message)
37 except socket.error:
38     #Send failed
39     print 'Send failed'
40     sys.exit()
41  
42 print 'Message send successfully'

上述例子中,首先連接到目標服務器,然后發送字符串數據 "GET / HTTP/1.1\r\n\r\n" ,這是一個 HTTP 協議的命令,用來獲取網站首頁的內容。

接下來需要讀取服務器返回的數據。

接收數據

recv 函數用於從 socket 接收數據:

01 #Socket client example in python
02  
03 import socket   #for sockets
04 import sys  #for exit
05  
06 #create an INET, STREAMing socket
07 try:
08     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
09 except socket.error:
10     print 'Failed to create socket'
11     sys.exit()
12      
13 print 'Socket Created'
14  
15 host = 'oschina.net';
16 port = 80;
17  
18 try:
19     remote_ip = socket.gethostbyname( host )
20  
21 except socket.gaierror:
22     #could not resolve
23     print 'Hostname could not be resolved. Exiting'
24     sys.exit()
25  
26 #Connect to remote server
27 s.connect((remote_ip , port))
28  
29 print 'Socket Connected to ' + host + ' on ip ' + remote_ip
30  
31 #Send some data to remote server
32 message = "GET / HTTP/1.1\r\nHost: oschina.net\r\n\r\n"
33  
34 try :
35     #Set the whole string
36     s.sendall(message)
37 except socket.error:
38     #Send failed
39     print 'Send failed'
40     sys.exit()
41  
42 print 'Message send successfully'
43  
44 #Now receive data
45 reply = s.recv(4096)
46  
47 print reply

下面是上述程序執行的結果:

01 $ python client.py
02 Socket Created
03 Ip address of oschina.net is 61.145.122.
04 Socket Connected to oschina.net on ip 61.145.122.155
05 Message send successfully
06 HTTP/1.1 301 Moved Permanently
07 Server: nginx
08 Date: Wed, 24 Oct 2012 13:26:46 GMT
09 Content-Type: text/html
10 Content-Length: 178
11 Connection: keep-alive
12 Keep-Alive: timeout=20

oschina.net 回應了我們所請求的 URL 的內容,很簡單。數據接收完了,可以關閉 Socket 了。

關閉 socket

close 函數用於關閉 Socket:

1 s.close()

這就是了。

讓我們回顧一下

上述的示例中我們學到了如何:

1. 創建 Socket
2. 連接到遠程服務器
3. 發送數據
4. 接收回應

當你用瀏覽器打開 www.oschina.net 時,其過程也是一樣。包含兩種類型,分別是客戶端和服務器,客戶端連接到服務器並讀取數據,服務器使用 Socket 接收進入的連接並提供數據。因此在這里 www.oschina.net 是服務器端,而你的瀏覽器是客戶端。

接下來我們開始在服務器端做點編碼。

服務器端編程

服務器端編程主要包括下面幾步:

1. 打開 socket
2. 綁定到一個地址和端口
3. 偵聽進來的連接
4. 接受連接
5. 讀寫數據

我們已經學習過如何打開 Socket 了,下面是綁定到指定的地址和端口上。

綁定 Socket

bind 函數用於將 Socket 綁定到一個特定的地址和端口,它需要一個類似 connect 函數所需的 sockaddr_in 結構體。

示例代碼:

01 import socket
02 import sys
03  
04 HOST = ''   # Symbolic name meaning all available interfaces
05 PORT = 8888 # Arbitrary non-privileged port
06  
07 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
08 print 'Socket created'
09  
10 try:
11     s.bind((HOST, PORT))
12 except socket.error , msg:
13     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
14     sys.exit()
15      
16 print 'Socket bind complete'

綁定完成后,就需要讓 Socket 開始偵聽連接。很顯然,你不能將兩個不同的 Socket 綁定到同一個端口之上。

連接偵聽

綁定 Socket 之后就可以開始偵聽連接,我們需要將 Socket 變成偵聽模式。socket 的 listen 函數用於實現偵聽模式:

1 s.listen(10)
2 print 'Socket now listening'

listen 函數所需的參數成為 backlog,用來控制程序忙時可保持等待狀態的連接數。這里我們傳遞的是 10,意味着如果已經有 10 個連接在等待處理,那么第 11 個連接將會被拒絕。當檢查了 socket_accept 后這個會更加清晰。

接受連接

示例代碼:

01 import socket
02 import sys
03  
04 HOST = ''   # Symbolic name meaning all available interfaces
05 PORT = 8888 # Arbitrary non-privileged port
06  
07 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
08 print 'Socket created'
09  
10 try:
11     s.bind((HOST, PORT))
12 except socket.error , msg:
13     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
14     sys.exit()
15      
16 print 'Socket bind complete'
17  
18 s.listen(10)
19 print 'Socket now listening'
20  
21 #wait to accept a connection - blocking call
22 conn, addr = s.accept()
23  
24 #display client information
25 print 'Connected with ' + addr[0] + ':' + str(addr[1])

輸出

運行該程序將會顯示:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening

現在這個程序開始等待連接進入,端口是 8888,請不要關閉這個程序,我們來通過 telnet 程序來進行測試。

打開命令行窗口並輸入:

1 $ telnet localhost 8888
2  
3 It will immediately show
4 $ telnet localhost 8888
5 Trying 127.0.0.1...
6 Connected to localhost.
7 Escape character is '^]'.
8 Connection closed by foreign host.

而服務器端窗口顯示的是:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening
5 Connected with 127.0.0.1:59954

我們可看到客戶端已經成功連接到服務器。

上面例子我們接收到連接並立即關閉,這樣的程序沒什么實際的價值,連接建立后一般會有大量的事情需要處理,因此讓我們來給客戶端做出點回應吧。

sendall 函數可通過 Socket 給客戶端發送數據:

01 import socket
02 import sys
03  
04 HOST = ''   # Symbolic name meaning all available interfaces
05 PORT = 8888 # Arbitrary non-privileged port
06  
07 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
08 print 'Socket created'
09  
10 try:
11     s.bind((HOST, PORT))
12 except socket.error , msg:
13     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
14     sys.exit()
15      
16 print 'Socket bind complete'
17  
18 s.listen(10)
19 print 'Socket now listening'
20  
21 #wait to accept a connection - blocking call
22 conn, addr = s.accept()
23  
24 print 'Connected with ' + addr[0] + ':' + str(addr[1])
25  
26 #now keep talking with the client
27 data = conn.recv(1024)
28 conn.sendall(data)
29  
30 conn.close()
31 s.close()

繼續運行上述代碼,然后打開另外一個命令行窗口輸入下面命令:

1 $ telnet localhost 8888
2 Trying 127.0.0.1...
3 Connected to localhost.
4 Escape character is '^]'.
5 happy
6 happy
7 Connection closed by foreign host.

可看到客戶端接收到來自服務器端的回應內容。

上面的例子還是一樣,服務器端回應后就立即退出了。而一些真正的服務器像 www.oschina.net 是一直在運行的,時刻接受連接請求。

也就是說服務器端應該一直處於運行狀態,否則就不能成為“服務”,因此我們要讓服務器端一直運行,最簡單的方法就是把 accept 方法放在一個循環內。

一直在運行的服務器

對上述代碼稍作改動:

01 import socket
02 import sys
03  
04 HOST = ''   # Symbolic name meaning all available interfaces
05 PORT = 8888 # Arbitrary non-privileged port
06  
07 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
08 print 'Socket created'
09  
10 try:
11     s.bind((HOST, PORT))
12 except socket.error , msg:
13     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
14     sys.exit()
15      
16 print 'Socket bind complete'
17  
18 s.listen(10)
19 print 'Socket now listening'
20  
21 #now keep talking with the client
22 while 1:
23     #wait to accept a connection - blocking call
24     conn, addr = s.accept()
25     print 'Connected with ' + addr[0] + ':' + str(addr[1])
26      
27     data = conn.recv(1024)
28     reply = 'OK...' + data
29     if not data:
30         break
31      
32     conn.sendall(reply)
33  
34 conn.close()
35 s.close()

很簡單只是加多一個 while 1 語句而已。

繼續運行服務器,然后打開另外三個命令行窗口。每個窗口都使用 telnet 命令連接到服務器:

1 $ telnet localhost 5000
2 Trying 127.0.0.1...
3 Connected to localhost.
4 Escape character is '^]'.
5 happy
6 OK .. happy
7 Connection closed by foreign host.


服務器所在的終端窗口顯示的是:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening
5 Connected with 127.0.0.1:60225
6 Connected with 127.0.0.1:60237
7 Connected with 127.0.0.1:60239


你看服務器再也不退出了,好吧,用 Ctrl+C 關閉服務器,所有的 telnet 終端將會顯示 "Connection closed by foreign host."

已經很不錯了,但是這樣的通訊效率太低了,服務器程序使用循環來接受連接並發送回應,這相當於是一次最多處理一個客戶端的請求,而我們要求服務器可同時處理多個請求。

處理多個連接

為了處理多個連接,我們需要一個獨立的處理代碼在主服務器接收到連接時運行。一種方法是使用線程,服務器接收到連接然后創建一個線程來處理連接收發數據,然后主服務器程序返回去接收新的連接。

下面是我們使用線程來處理連接請求:

01 import socket
02 import sys
03 from thread import *
04  
05 HOST = ''   # Symbolic name meaning all available interfaces
06 PORT = 8888 # Arbitrary non-privileged port
07  
08 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
09 print 'Socket created'
10  
11 #Bind socket to local host and port
12 try:
13     s.bind((HOST, PORT))
14 except socket.error , msg:
15     print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
16     sys.exit()
17      
18 print 'Socket bind complete'
19  
20 #Start listening on socket
21 s.listen(10)
22 print 'Socket now listening'
23  
24 #Function for handling connections. This will be used to create threads
25 def clientthread(conn):
26     #Sending message to connected client
27     conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
28      
29     #infinite loop so that function do not terminate and thread do not end.
30     while True:
31          
32         #Receiving from client
33         data = conn.recv(1024)
34         reply = 'OK...' + data
35         if not data:
36             break
37      
38         conn.sendall(reply)
39      
40     #came out of loop
41     conn.close()
42  
43 #now keep talking with the client
44 while 1:
45     #wait to accept a connection - blocking call
46     conn, addr = s.accept()
47     print 'Connected with ' + addr[0] + ':' + str(addr[1])
48      
49     #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
50     start_new_thread(clientthread ,(conn,))
51  
52 s.close()

運行上述服務端程序,然后像之前一樣打開三個終端窗口並執行 telent 命令:

01 $ telnet localhost 8888
02 Trying 127.0.0.1...
03 Connected to localhost.
04 Escape character is '^]'.
05 Welcome to the server. Type something and hit enter
06 hi
07 OK...hi
08 asd
09 OK...asd
10 cv
11 OK...cv

服務器端所在終端窗口輸出信息如下:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening
5 Connected with 127.0.0.1:60730
6 Connected with 127.0.0.1:60731


線程接管了連接並返回相應數據給客戶端。

這便是我們所要介紹的服務器端編程。

結論

到這里為止,你已經學習了 Python 的 Socket 基本編程,你可自己動手編寫一些例子來強化這些知識。

你可能會遇見一些問題:Bind failed. Error Code : 98 Message Address already in use,碰見這種問題只需要簡單更改服務器端口即可。

英文原文OSCHINA 原創翻譯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM