由於最近要開發一款服務器、多客戶端應用,自然而然地想到了要用Socket模塊。
此模塊官方有資料,詳見socket --- 底層網絡接口 — Python 3.9.5 文檔。函數 socket()
返回一個 套接字對象 ,其方法是對各種套接字系統調用的實現。
具體操作如下:
一、客戶端編程
1.創建Socket
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
上述代碼使用了下面兩個屬性來創建 Socket:
- 地址簇 : AF_INET (IPv4)
- 類型: SOCK_STREAM (使用 TCP 傳輸控制協議)
2.錯誤處理
如果 socket 函數失敗了,python 將拋出一個名為 socket.error 的異常,這個異常必須予以處理:
1 #handling errors in python socket programs 2 3 import socket #for sockets 4 import sys #for exit 5 6 try: 7 #create an AF_INET, STREAM socket (TCP) 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 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'
3.連接到服務器
連接到服務器需要服務器地址和端口號。
1 import socket #for sockets 2 import sys #for exit 3 4 try: 5 #create an AF_INET, STREAM socket (TCP) 6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 except socket.error, msg: 8 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 9 sys.exit(); 10 11 print 'Socket Created' 12 #or IP here 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地址,接下來還需要端口信息。
1 import socket #for sockets 2 import sys #for exit 3 4 try: 5 #create an AF_INET, STREAM socket (TCP) 6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 except socket.error, msg: 8 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 9 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
運行后得到的結果如下。
$ 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 並進行連接,已經連接上了,接下來就是往服務器上發送數據。
4.發送數據。
sendall 函數用於簡單的發送數據,我們來向 oschina 發送一些數據:
1 import socket #for sockets 2 import sys #for exit 3 4 try: 5 #create an AF_INET, STREAM socket (TCP) 6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 except socket.error, msg: 8 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 9 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.encode("utf-8"))
37 except socket.error: 38 #Send failed 39 print 'Send failed' 40 sys.exit() 41 42 print 'Message send successfully'
注意:s.sendall函數里面的內容必須加上.encode("utf-8"),否則會報錯。
上述例子中,首先連接到目標服務器,然后發送字符串數據 "GET / HTTP/1.1\r\n\r\n" ,這是一個 HTTP 協議的命令,用來獲取網站首頁的內容。
接下來需要讀取服務器返回的數據。
5.接收數據
recv 函數用於從 socket 接收數據:
1 #Socket client example in python 2 3 import socket #for sockets 4 import sys #for exit 5 6 #create an INET, STREAMing socket 7 try: 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 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
下面是上述程序執行的結果:
$ 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/
http://oschina.net 回應了我們所請求的 URL 的內容,很簡單。數據接收完了,可以關閉 Socket 了。
6.關閉SOCKET
close 函數用於關閉 Socket:
s.close()
二、服務器端編程
服務器端編程主要包括下面幾步:
- 打開 socket
- 綁定到一個地址和端口
- 偵聽進來的連接
- 接受連接
- 讀寫數據
我們已經學習過如何打開 Socket 了,下面是綁定到指定的地址和端口上。
綁定 Socket
bind 函數用於將 Socket 綁定到一個特定的地址和端口,它需要一個類似 connect 函數所需的 sockaddr_in 結構體。
示例代碼:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 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 后這個會更加清晰。
接受連接
示例代碼:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 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])
輸出
運行該程序將會顯示
$ 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 給客戶端發送數據:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 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()
繼續運行上述代碼,然后打開另外一個命令行窗口輸入下面命令:
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
happy
Connection closed by foreign host.
可看到客戶端接收到來自服務器端的回應內容。
上面的例子還是一樣,服務器端回應后就立即退出了。而一些真正的服務器像 http://www.oschina.net 是一直在運行的,時刻接受連接請求。
也就是說服務器端應該一直處於運行狀態,否則就不能成為“服務”,因此我們要讓服務器端一直運行,最簡單的方法就是把 accept 方法放在一個循環內。
一直在運行的服務器
對上述代碼稍作改動:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 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 命令連接到服務器:
$ 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."
已經很不錯了,但是這樣的通訊效率太低了,服務器程序使用循環來接受連接並發送回應,這相當於是一次最多處理一個客戶端的請求,而我們要求服務器可同時處理多個請求。
處理多個連接
為了處理多個連接,我們需要一個獨立的處理代碼在主服務器接收到連接時運行。一種方法是使用線程,服務器接收到連接然后創建一個線程來處理連接收發數據,然后主服務器程序返回去接收新的連接。
下面是我們使用線程來處理連接請求:
1 import socket 2 import sys 3 from thread import * 4 5 HOST = '' # Symbolic name meaning all available interfaces 6 PORT = 8888 # Arbitrary non-privileged port 7 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 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 命令:
$ 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
線程接管了連接並返回相應數據給客戶端。
這便是我們所要介紹的服務器端編程。