Python學習之旅-20

Socket 是進程間通信的一種方式,它與其他進程間通信的一個主要不同是:它能實現不同主機間的進程間通信,我們網絡上各種各樣的服務大多都是基於 Socket 來完成通信的,例如我們每天瀏覽網頁、QQ 聊天、收發 email 等等。要解決網絡上兩臺主機之間的進程通信問題,首先要唯一標識該進程,在 TCP/IP 網絡協議中,就是通過 (IP地址,協議,端口號) 三元組來標識進程的,解決了進程標識問題,就有了通信的基礎了。

本文主要介紹使用 Python 進行 TCP Socket 網絡編程,假設你已經具有初步的網絡知識及 Python 基本語法知識。

TCP 是一種面向連接的傳輸層協議,TCP Socket 是基於一種 Client-Server 的編程模型,服務端監聽客戶端的連接請求,一旦建立連接即可以進行傳輸數據。那麼對 TCP Socket 編程的介紹也分爲客戶端和服務端:

客戶端編程

創建 socket

首先要創建 socket,用 Python 中 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 的描述符,將在後面相關函數中使用。該函數帶有兩個參數:

  • Address Family:可以選擇 AF_INET(用於 Internet 進程間通信) 或者 AF_UNIX(用於同一臺機器進程間通信)
  • Type:套接字類型,可以是 SOCKET_STREAM(流式套接字,主要用於 TCP 協議)或者SOCKET_DGRAM(數據報套接字,主要用於 UDP 協議)

注:由於本文主要概述一下 Python Socket 編程的過程,因此不會對相關函數參數、返回值進行詳細介紹,需要了解的可以查看相關手冊

錯誤處理

如果創建 socket 函數失敗,會拋出一個 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 來連接某個服務器,就連 www.google.com 吧。

連接服務器

本文開始也提到了,socket 使用 (IP地址,協議,端口號) 來標識一個進程,那麼我們要想和服務器進行通信,就需要知道它的 IP地址以及端口號。

獲得遠程主機的 IP 地址

Python 提供了一個簡單的函數 socket.gethostbyname 來獲得遠程主機的 IP 地址:

host = 'www.google.com'
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

現在我們知道了服務器的 IP 地址,就可以使用連接函數 connect 連接到該 IP 的某個特定的端口上了,下面例子連接到 80 端口上(是 HTTP 服務的默認端口):

#Connect to remote server
s.connect((remote_ip , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

運行該程序:

$ python client.py
Socket created
Ip of remote host www.google.com is 173.194.38.145
Socket Connected to www.google.com on ip 173.194.38.145

發送數據

上面說明連接到 www.google.com 已經成功了,接下面我們可以向服務器發送一些數據,例如發送字符串GET / HTTP/1.1\r\n\r\n,這是一個 HTTP 請求網頁內容的命令。

#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'

發送完數據之後,客戶端還需要接受服務器的響應。

接收數據

函數 recv 可以用來接收 socket 的數據:

#Now receive data
reply = s.recv(4096)

print reply

一起運行的結果如下:

Socket created
Ip of remote host www.google.com is 173.194.38.145
Socket Connected to www.google.com on ip 173.194.38.145
Message send successfully
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ
Content-Length: 262
Date: Thu, 11 Dec 2014 08:47:58 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic,p=0.02

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.com.sg/?gfe_rd=cr&ei=PlqJVLCREovW8gfF0oG4CQ">here</A>.
</BODY></HTML>

關閉 socket

當我們不想再次請求服務器數據時,可以將該 socket 關閉,結束這次通信:

s.close()

小結

上面我們學到了如何:

  1. 創建 socket
  2. 連接到遠程服務器
  3. 發送數據
  4. 接收數據
  5. 關閉 socket

當我們打開 www.google.com 時,瀏覽器所做的就是這些,知道這些是非常有意義的。在 socket 中具有這種行爲特徵的被稱爲CLIENT,客戶端主要是連接遠程系統獲取數據。

socket 中另一種行爲稱爲SERVER,服務器使用 socket 來接收連接以及提供數據,和客戶端正好相反。所以 www.google.com 是服務器,你的瀏覽器是客戶端,或者更準確地說,www.google.com 是 HTTP 服務器,你的瀏覽器是 HTTP 客戶端。

那麼上面介紹了客戶端的編程,現在輪到服務器端如果使用 socket 了。

服務器端編程

服務器端主要做以下工作:

  • 打開 socket
  • 綁定到特定的地址以及端口上
  • 監聽連接
  • 建立連接
  • 接收/發送數據

上面已經介紹瞭如何創建 socket 了,下面一步是綁定。

綁定 socket

函數 bind 可以用來將 socket 綁定到特定的地址和端口上,它需要一個 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'

綁定完成之後,接下來就是監聽連接了。

監聽連接

函數 listen 可以將 socket 置於監聽模式:

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

該函數帶有一個參數稱爲 backlog,用來控制連接的個數。如果設爲 10,那麼有 10 個連接正在等待處理,此時第 11 個請求過來時將會被拒絕。

接收連接

當有客戶端向服務器發送連接請求時,服務器會接收連接:

#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 端口上等待請求的到來。不要關掉這個程序,讓它一直運行,現在客戶端可以通過該端口連接到 socket。我們用 telnet 客戶端來測試,打開一個終端,輸入 telnet localhost 8888

$ 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

我們觀察到客戶端已經連接上服務器了。在建立連接之後,我們可以用來與客戶端進行通信。下面例子演示的是,服務器建立連接之後,接收客戶端發送來的數據,並立即將數據發送回去,下面是完整的服務端程序:

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 連接服務器,隨便輸入字符串,你會看到:

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
happy
Connection closed by foreign host.

客戶端(telnet)接收了服務器的響應。

我們在完成一次響應之後服務器立即斷開了連接,而像 www.google.com 這樣的服務器總是一直等待接收連接的。我們需要將上面的服務器程序改造成一直運行,最簡單的辦法是將 accept 放到一個循環中,那麼就可以一直接收連接了。

保持服務

我們可以將代碼改成這樣讓服務器一直工作:

import socket
import sys

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 5000 # 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()

現在在一個終端下運行上面的服務器程序,再開啓三個終端,分別用 telnet 去連接,如果一個終端連接之後不輸入數據其他終端是沒辦法進行連接的,而且每個終端只能服務一次就斷開連接。這從代碼上也是可以看出來的。

這顯然也不是我們想要的,我們希望多個客戶端可以隨時建立連接,而且每個客戶端可以跟服務器進行多次通信,這該怎麼修改呢?

處理連接

爲了處理每個連接,我們需要將處理的程序與主程序的接收連接分開。一種方法可以使用線程來實現,主服務程序接收連接,創建一個線程來處理該連接的通信,然後服務器回到接收其他連接的邏輯上來。

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()

再次運行上面的程序,打開三個終端來與主服務器建立 telnet 連接,這時候三個客戶端可以隨時接入,而且每個客戶端可以與主服務器進行多次通信。

telnet 終端下可能輸出如下:

$ 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

要結束 telnet 的連接,按下 Ctrl-] 鍵,再輸入 close 命令。

服務器終端的輸出可能是這樣的:

$ 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
發佈了51 篇原創文章 · 獲贊 10 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章