這是用來快速學習 Python Socket 套接字編程的指南和教程。Python 的 Socket 編程跟 C 語言很像。
Python 官方關于 Socket 的函數請看 http://docs.python.org/library/socket.html
基本上,Socket 是任何一種計算機網絡通訊中最基礎的內容。例如當你在瀏覽器地址欄中輸入 www.jb51.net 時,你會打開一個套接字,然后連接到 www.jb51.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.jb51.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.jb51.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.jb51.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.jb51.net is 61.145.122.155
Socket Connected to www.jb51.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.jb51.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 = 'jb51.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: jb51.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 jb51.net is 61.145.122.
Socket Connected to jb51.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: //www.jb51.net/
jb51.net 回應了我們所請求的 URL 的內容,很簡單。數據接收完了,可以關閉 Socket 了。
關閉 socket
close 函數用于關閉 Socket:
這就是了。
讓我們回顧一下
上述的示例中我們學到了如何:
1. 創建 Socket
2. 連接到遠程服務器
3. 發送數據
4. 接收回應
當你用瀏覽器打開 www.jb51.net 時,其過程也是一樣。包含兩種類型,分別是客戶端和服務器,客戶端連接到服務器并讀取數據,服務器使用 Socket 接收進入的連接并提供數據。因此在這里 www.jb51.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])
輸出
運行該程序將會顯示:
Socket created
Socket bind complete
Socket now listening
現在這個程序開始等待連接進入,端口是 8888,請不要關閉這個程序,我們來通過 telnet 程序來進行測試。
打開命令行窗口并輸入:
It will immediately show
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
而服務器端窗口顯示的是:
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()
繼續運行上述代碼,然后打開另外一個命令行窗口輸入下面命令:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
happy
Connection closed by foreign host.
可看到客戶端接收到來自服務器端的回應內容。
上面的例子還是一樣,服務器端回應后就立即退出了。而一些真正的服務器像 www.jb51.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 命令連接到服務器:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
OK .. happy
Connection closed by foreign host.
服務器所在的終端窗口顯示的是:
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 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 命令:
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
服務器端所在終端窗口輸出信息如下:
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,碰見這種問題只需要簡單更改服務器端口即可。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
