1. 程式人生 > >Python 網路程式設計基礎入門

Python 網路程式設計基礎入門

Python 網路程式設計基礎入門

Python的網路程式設計主要支援兩種網路協議:TCP和UDP。這兩種協議都通過叫Socket的程式設計抽象進行處理。Socket起源於Unix,是類似於檔案的存在,可以像檔案一樣進行I/O、開啟、關閉等操作,最主要的是它可以實現網路上不同主機的程序間通訊,所以基本上Socket是任何一種網路通訊中最基礎的內容。

進群進群:700341555可以獲取Python各類入門學習資料!

這是我的微信公眾號【Python程式設計之家】各位大佬用空可以關注下,每天更新Python學習方法,感謝!

111111111111.png

 

Python中建立一個套接字很簡單:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. import socket

  2. s = socket.socket(family, type)

</pre>

地址族

family為地址族,該族指定要使用的網路協議,主要使用的有:

  • AF_INET:IPv4協議(TCP,UDP)

  • AF_INET6:IPv6協議(TCP,UDP)

  • AF_UNIX:UNIX域協議,用於同一臺機器的程序間通訊

套接字型別

type為套接字型別,指定給定的協議組中使用的通訊型別:

  • SOCK_STREAM:用於TCP

  • SOCK_DGRAM:用於UDP

TCP和UDP都是基於Client/Server的程式設計模型,所以Socket程式設計也分為客戶端和伺服器端,以TCP為例:

TCP客戶端程式設計

要獲取遠端主機的ip地址,可以使用socket標準庫提供的gethostbyname方法:

socket套接字例項s可用於客戶端的方法有以下幾個:

  • s.connect(addr):連線伺服器端套接字。addr格式取決於地址族,對於IPv4來說,是一個包含ip地址與埠的元組,(host, port)。連線失敗會報socket.error錯誤。

  • s.sendall(string):嘗試傳送所有資料,成功則返回None,失敗則報異常。

  • s.recv(bufsize):接收資料,bufsize指定接收的最大資料量。

  • s.close:關閉套接字

OK,現在可以用socket向遠端主機發送一個HTTP GET請求了:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立套接字

  4. host = 'www.baidu.com'

  5. port = 80

  6. ip = socket.gethostbyname(host) #獲取ip

  7. s.connect((ip, port)) #建立連線

  8. message = 'GET / HTTP/1.1rnrn'

  9. s.sendall(message) #傳送GET請求

  10. r = s.recv(4096) #接收資料

  11. print r

  12. s.close #關閉套接字

</pre>

返回:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. HTTP/1.1 302 Moved Temporarily

  2. Date: Wed, 10 Jan 2018 18:56:45 GMT

  3. Content-Type: text/html

  4. Content-Length: 225

  5. Connection: Keep-Alive

  6. Location: http://www.baidu.com/search/error.html

  7. Server: BWS/1.1

  8. X-UA-Compatible: IE=Edge,chrome=1

  9. BDPAGETYPE: 3

  10. Set-Cookie: BDSVRTM=0; path=/

</pre>

下面我們可以實現自己的伺服器。

TCP伺服器端程式設計

Socket例項與伺服器端程式設計有關的方法有以下幾個:

  • s.bind(addr):addr也是(host, port)形式的元組,將套接字繫結到特定的地址和埠上。空字串表示任意地址,'broadcast'可以用做傳送廣播資訊。

  • s.listen(backlog):開始監聽連線,backlog為最大掛起連線次數。

  • s.accept:返回元組(conn,addr),conn為新的套接字,可以用來發送和接收資料。addr是客戶端的套接字地址。

  • s.recv、s.sendall和s.close與客戶端同。

現在寫一個將客戶端傳送來的資訊傳送回去的伺服器:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. import sys

  4. HOST = ''

  5. PORT = 8088

  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  7. s.bind((HOST, PORT))

  8. s.listen(5)

  9. print '開始監聽'

  10. conn, addr = s.accept

  11. print 'Connected with ' + addr[0] + ':' + str(addr[1])

  12. data = conn.recv(1024)

  13. conn.sendall(data)

  14. conn.close

  15. s.close

</pre>

執行:

伺服器開始監聽連線了。修改一下剛才寫的客戶端程式:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  4. host = 'localhost'

  5. port = 8088

  6. s.connect((host, port)) #建立連線

  7. message = 'GET / HTTP/1.1rnrn'

  8. s.sendall(message) #傳送GET請求

  9. r = s.recv(4096) #接收資料

  10. print r

  11. s.close #關閉套接字

</pre>

執行,連線本地的伺服器,伺服器端輸出:

連線成功。客戶端輸出:

傳送的訊息被返回了。

這就是一個最簡單的伺服器了。上述伺服器只能處理一次連線,這顯然不是我們想看到的,保持一直執行:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. import sys

  4. HOST = ''

  5. PORT = 8088

  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  7. s.bind((HOST, PORT))

  8. s.listen(5)

  9. print '開始監聽'

  10. while True:

  11. conn, addr = s.accept

  12. print 'Connected with ' + addr[0] + ':' + str(addr[1])

  13. data = conn.recv(1024)

  14. conn.sendall(data)

  15. conn.close

  16. s.close

</pre>

現在就可以使用客戶端無限連線了:

伺服器端多執行緒處理連線

現在伺服器端雖然可以處理無限多個連線,但只能一個一個的處理,後面的客戶端連線只能等待前面的連線完成才能傳送資料。要同時處理多個連線,可以使用多執行緒。伺服器端接收到新的連線後,開啟一個執行緒處理新連線,主執行緒去建立下一個連線。

伺服器端:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. import threading

  4. HOST = ''

  5. PORT = 8088

  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  7. s.bind((HOST, PORT))

  8. s.listen(5)

  9. print '開始監聽'

  10. def runThread(conn):

  11. data = conn.recv(1024)

  12. print data

  13. conn.sendall(data)

  14. conn.close

  15. while True:

  16. conn, addr = s.accept

  17. print 'Connected with ' + addr[0] + ':' + str(addr[1])

  18. t = threading.Thread(target=runThread, args=(conn,))

  19. t.daemon = True

  20. t.start

</pre>

客戶端啟動多個連線:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. import time

  4. import threading

  5. def run:

  6. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  7. host = 'localhost'

  8. port = 8088

  9. s.connect((host, port))

  10. message = 'GET / HTTP/1.1rnrn'

  11. s.sendall(message)

  12. print s.recv(4096)

  13. s.close

  14. if __name__ == '__main__':

  15. for i in xrange(4):

  16. t = threading.Thread(target=run)

  17. t.start

</pre>

執行:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. 開始監聽

  2. Connected with 127.0.0.1:61772

  3. GET / HTTP/1.1

  4. Connected with 127.0.0.1:61773

  5. GET / HTTP/1.1

  6. Connected with 127.0.0.1:61774

  7. GET / HTTP/1.1

  8. Connected with 127.0.0.1:61775

  9. GET / HTTP/1.1

</pre>

UDP程式設計

UDP與TCP的不同之處在於UDP是不用建立連線的。

在此需要使用s.recvfrom與s.sendto方法,前者與s.recv相同,但返回(data, addr)的元組,addr為資料傳送端的套接字地址,後者傳送資料時需要加入要傳送的遠端地址。

伺服器:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

  4. s.bind(('', 10000))

  5. while True:

  6. data, addr = s.recvfrom(1024)

  7. print '接收到%s的連線'%str(addr)

  8. s.sendto(data, addr)

</pre>

客戶端:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">

  1. # -*- coding: utf-8 -*-

  2. import socket

  3. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

  4. s.sendto('Hello World', ('localhost', 10000))

  5. r, addr = s.recvfrom(1024)

  6. print r

  7. s.close

</pre>