這是用來快速學習 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 函數可以實現,代碼如下:
#Socket client example in python
import
socket
#for sockets
#create an AF_INET, STREAM socket (TCP)
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print
'Socket Created'
函數 socket.socket 創建了一個 Socket,並返回 Socket 的描述符可用於其他 Socket 相關的函數。
上述代碼使用了下面兩個屬性來創建 Socket:
地址簇 : AF_INET (IPv4)
類型: SOCK_STREAM (使用 TCP 傳輸控制協議)
錯誤處理
如果 socket 函數失敗了,python 將拋出一個名爲 socket.error 的異常,這個異常必須予以處理:
#handling errors in python socket programs
import
socket
#for sockets
import
sys
#for exit
try
:
#create an AF_INET, STREAM socket (TCP)
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except
socket.error, msg:
print
'Failed to create socket. Error code: '
+
str
(msg[
0
])
+
' , Error message : '
+
msg[
1
]
sys.exit();
print
'Socket Created'
好了,假設你已經成功創建了 Socket,下一步該做什麼呢?接下來我們將使用這個 Socket 來連接到服務器。
注意
與 SOCK_STREAM 相對應的其他類型是 SOCK_DGRAM 用於 UDP 通訊協議,UDP 通訊是非連接 Socket,在這篇文章中我們只討論 SOCK_STREAM ,或者叫 TCP 。
連接到服務器
連接到服務器需要服務器地址和端口號,這裏使用的是 www.oschina.net 和 80 端口。
首先獲取遠程主機的 IP 地址
連接到遠程主機之前,我們需要知道它的 IP 地址,在 Python 中,獲取 IP 地址是很簡單的:
import
socket
#for sockets
import
sys
#for exit
try
:
#create an AF_INET, STREAM socket (TCP)
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except
socket.error, msg:
print
'Failed to create socket. Error code: '
+
str
(msg[
0
])
+
' , Error message : '
+
msg[
1
]
sys.exit();
print
'Socket Created'
host
=
'www.oschina.net'
try
:
remote_ip
=
socket.gethostbyname( host )
except
socket.gaierror:
#could not resolve
print
'Hostname could not be resolved. Exiting'
sys.exit()
print
'Ip address of '
+
host
+
' is '
+
remote_ip
我們已經有 IP 地址了,接下來需要指定要連接的端口。
代碼:
import
socket
#for sockets
import
sys
#for exit
try
:
#create an AF_INET, STREAM socket (TCP)
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except
socket.error, msg:
print
'Failed to create socket. Error code: '
+
str
(msg[
0
])
+
' , Error message : '
+
msg[
1
]
sys.exit();
print
'Socket Created'
host
=
'www.oschina.net'
port
=
80
try
:
remote_ip
=
socket.gethostbyname( host )
except
socket.gaierror:
#could not resolve
print
'Hostname could not be resolved. Exiting'
sys.exit()
print
'Ip address of '
+
host
+
' is '
+
remote_ip
#Connect to remote server
s.connect((remote_ip , port))
print
'Socket Connected to '
+
host
+
' on ip '
+
remote_ip
現在運行程序
$ python client.py
Socket Created
Ip address of www.oschina.net is 61.145.122.155
Socket Connected to www.oschina.net on ip 61.145.122.155
這段程序創建了一個 Socket 並進行連接,試試使用其他一些不存在的端口(如81)會是怎樣?這個邏輯相當於構建了一個端口掃描器。
已經連接上了,接下來就是往服務器上發送數據。
免費提示
使用 SOCK_STREAM/TCP 套接字纔有“連接”的概念。連接意味着可靠的數據流通訊機制,可以同時有多個數據流。可以想象成一個數據互不干擾的管道。另外一個重要的提示是:數據包的發送和接收是有順序的。
其他一些 Socket 如 UDP、ICMP 和 ARP 沒有“連接”的概念,它們是無連接通訊,意味着你可從任何人或者給任何人發送和接收數據包。
發送數據
sendall 函數用於簡單的發送數據,我們來向 oschina 發送一些數據:
import
socket
#for sockets
import
sys
#for exit
try
:
#create an AF_INET, STREAM socket (TCP)
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except
socket.error, msg:
print
'Failed to create socket. Error code: '
+
str
(msg[
0
])
+
' , Error message : '
+
msg[
1
]
sys.exit();
print
'Socket Created'
host
=
'www.oschina.net'
port
=
80
try
:
remote_ip
=
socket.gethostbyname( host )
except
socket.gaierror:
#could not resolve
print
'Hostname could not be resolved. Exiting'
sys.exit()
print
'Ip address of '
+
host
+
' is '
+
remote_ip
#Connect to remote server
s.connect((remote_ip , port))
print
'Socket Connected to '
+
host
+
' on ip '
+
remote_ip
#Send some data to remote server
message
=
"GET / HTTP/1.1\r\n\r\n"
try
:
#Set the whole string
s.sendall(message)
except
socket.error:
#Send failed
print
'Send failed'
sys.exit()
print
'Message send successfully'
上述例子中,首先連接到目標服務器,然後發送字符串數據 "GET / HTTP/1.1\r\n\r\n" ,這是一個 HTTP 協議的命令,用來獲取網站首頁的內容。
接下來需要讀取服務器返回的數據。
接收數據
recv 函數用於從 socket 接收數據:
#Socket client example in python
import
socket
#for sockets
import
sys
#for exit
#create an INET, STREAMing socket
try
:
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except
socket.error:
print
'Failed to create socket'
sys.exit()
print
'Socket Created'
host
=
'oschina.net'
;
port
=
80
;
try
:
remote_ip
=
socket.gethostbyname( host )
except
socket.gaierror:
#could not resolve
print
'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
print
'Socket Connected to '
+
host
+
' on ip '
+
remote_ip
#Send some data to remote server
message
=
"GET / HTTP/1.1\r\nHost: oschina.net\r\n\r\n"
try
:
#Set the whole string
s.sendall(message)
except
socket.error:
#Send failed
print
'Send failed'
sys.exit()
print
'Message send successfully'
#Now receive data
reply
=
s.recv(
4096
)
print
reply
下面是上述程序執行的結果:
$ python client.py
Socket Created
Ip address of oschina.net is 61.145.122.
Socket Connected to oschina.net on ip 61.145.122.155
Message send successfully
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Oct 2012 13:26:46 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Keep-Alive: timeout=20
Location: http://www.oschina.net/
oschina.net 迴應了我們所請求的 URL 的內容,很簡單。數據接收完了,可以關閉 Socket 了。
關閉 socket
close 函數用於關閉 Socket:
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 結構體。
示例代碼:
import
socket
import
sys
HOST
=
''
# Symbolic name meaning all available interfaces
PORT
=
8888
# Arbitrary non-privileged port
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print
'Socket created'
try
:
s.bind((HOST, PORT))
except
socket.error , msg:
print
'Bind failed. Error Code : '
+
str
(msg[
0
])
+
' Message '
+
msg[
1
]
sys.exit()
print
'Socket bind complete'
綁定完成後,就需要讓 Socket 開始偵聽連接。很顯然,你不能將兩個不同的 Socket 綁定到同一個端口之上。
連接偵聽
綁定 Socket 之後就可以開始偵聽連接,我們需要將 Socket 變成偵聽模式。socket 的 listen 函數用於實現偵聽模式:
s.listen(10)
print
'Socket now listening'
listen 函數所需的參數成爲 backlog,用來控制程序忙時可保持等待狀態的連接數。這裏我們傳遞的是 10,意味着如果已經有 10 個連接在等待處理,那麼第 11 個連接將會被拒絕。當檢查了 socket_accept 後這個會更加清晰。
接受連接
示例代碼:
import
socket
import
sys
HOST
=
''
# Symbolic name meaning all available interfaces
PORT
=
8888
# Arbitrary non-privileged port
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print
'Socket created'
try
:
s.bind((HOST, PORT))
except
socket.error , msg:
print
'Bind failed. Error Code : '
+
str
(msg[
0
])
+
' Message '
+
msg[
1
]
sys.exit()
print
'Socket bind complete'
s.listen(
10
)
print
'Socket now listening'
#wait to accept a connection - blocking call
conn, addr
=
s.accept()
#display client information
print
'Connected with '
+
addr[
0
]
+
':'
+
str
(addr[
1
])
輸出
運行該程序將會顯示:
$ python server.py
Socket created
Socket bind complete
Socket now listening
現在這個程序開始等待連接進入,端口是 8888,請不要關閉這個程序,我們來通過 telnet 程序來進行測試。
打開命令行窗口並輸入:
$ telnet localhost 8888
It will immediately show
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is
'^]'
.
Connection closed by foreign host.
而服務器端窗口顯示的是:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:59954
我們可看到客戶端已經成功連接到服務器。
上面例子我們接收到連接並立即關閉,這樣的程序沒什麼實際的價值,連接建立後一般會有大量的事情需要處理,因此讓我們來給客戶端做出點回應吧。
sendall 函數可通過 Socket 給客戶端發送數據:
import
socket
import
sys
HOST
=
''
# Symbolic name meaning all available interfaces
PORT
=
8888
# Arbitrary non-privileged port
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print
'Socket created'
try
:
s.bind((HOST, PORT))
except
socket.error , msg:
print
'Bind failed. Error Code : '
+
str
(msg[
0
])
+
' Message '
+
msg[
1
]
sys.exit()
print
'Socket bind complete'
s.listen(
10
)
print
'Socket now listening'
#wait to accept a connection - blocking call
conn, addr
=
s.accept()
print
'Connected with '
+
addr[
0
]
+
':'
+
str
(addr[
1
])
#now keep talking with the client
data
=
conn.recv(
1024
)
conn.sendall(data)
conn.close()
s.close()
繼續運行上述代碼,然後打開另外一個命令行窗口輸入下面命令:
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is
'^]'
.
happy
happy
Connection closed by foreign host.
可看到客戶端接收到來自服務器端的迴應內容。
上面的例子還是一樣,服務器端迴應後就立即退出了。而一些真正的服務器像 www.oschina.net 是一直在運行的,時刻接受連接請求。
也就是說服務器端應該一直處於運行狀態,否則就不能成爲“服務”,因此我們要讓服務器端一直運行,最簡單的方法就是把 accept 方法放在一個循環內。
一直在運行的服務器
對上述代碼稍作改動:
import
socket
import
sys
HOST
=
''
# Symbolic name meaning all available interfaces
PORT
=
8888
# Arbitrary non-privileged port
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print
'Socket created'
try
:
s.bind((HOST, PORT))
except
socket.error , msg:
print
'Bind failed. Error Code : '
+
str
(msg[
0
])
+
' Message '
+
msg[
1
]
sys.exit()
print
'Socket bind complete'
s.listen(
10
)
print
'Socket now listening'
#now keep talking with the client
while
1
:
#wait to accept a connection - blocking call
conn, addr
=
s.accept()
print
'Connected with '
+
addr[
0
]
+
':'
+
str
(addr[
1
])
data
=
conn.recv(
1024
)
reply
=
'OK...'
+
data
if
not
data:
break
conn.sendall(reply)
conn.close()
s.close()
很簡單只是加多一個 while 1 語句而已。
繼續運行服務器,然後打開另外三個命令行窗口。每個窗口都使用 telnet 命令連接到服務器:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is
'^]'
.
happy
OK .. happy
Connection closed by foreign host.
服務器所在的終端窗口顯示的是:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60225
Connected with 127.0.0.1:60237
Connected with 127.0.0.1:60239
你看服務器再也不退出了,好吧,用 Ctrl+C 關閉服務器,所有的 telnet 終端將會顯示 "Connection closed by foreign host."
已經很不錯了,但是這樣的通訊效率太低了,服務器程序使用循環來接受連接併發送回應,這相當於是一次最多處理一個客戶端的請求,而我們要求服務器可同時處理多個請求。
處理多個連接
爲了處理多個連接,我們需要一個獨立的處理代碼在主服務器接收到連接時運行。一種方法是使用線程,服務器接收到連接然後創建一個線程來處理連接收發數據,然後主服務器程序返回去接收新的連接。
下面是我們使用線程來處理連接請求:
import
socket
import
sys
from
thread
import
*
HOST
=
''
# Symbolic name meaning all available interfaces
PORT
=
8888
# Arbitrary non-privileged port
s
=
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print
'Socket created'
#Bind socket to local host and port
try
:
s.bind((HOST, PORT))
except
socket.error , msg:
print
'Bind failed. Error Code : '
+
str
(msg[
0
])
+
' Message '
+
msg[
1
]
sys.exit()
print
'Socket bind complete'
#Start listening on socket
s.listen(
10
)
print
'Socket now listening'
#Function for handling connections. This will be used to create threads
def
clientthread(conn):
#Sending message to connected client
conn.send(
'Welcome to the server. Type something and hit enter\n'
)
#send only takes string
#infinite loop so that function do not terminate and thread do not end.
while
True
:
#Receiving from client
data
=
conn.recv(
1024
)
reply
=
'OK...'
+
data
if
not
data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while
1
:
#wait to accept a connection - blocking call
conn, addr
=
s.accept()
print
'Connected with '
+
addr[
0
]
+
':'
+
str
(addr[
1
])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
運行上述服務端程序,然後像之前一樣打開三個終端窗口並執行 telent 命令:
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is
'^]'
.
Welcome to the server. Type something and hit enter
hi
OK...hi
asd
OK...asd
cv
OK...cv
服務器端所在終端窗口輸出信息如下:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with
127.0
.
0.1
:
60730
Connected with
127.0
.
0.1
:
60731
線程接管了連接並返回相應數據給客戶端。
這便是我們所要介紹的服務器端編程。
結論
到這裏爲止,你已經學習了 Python 的 Socket 基本編程,你可自己動手編寫一些例子來強化這些知識。
你可能會遇見一些問題:Bind failed. Error Code : 98 Message Address already in use,碰見這種問題只需要簡單更改服務器端口即可。