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;">
-
import socket
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立套接字
-
host = 'www.baidu.com'
-
port = 80
-
ip = socket.gethostbyname(host) #獲取ip
-
s.connect((ip, port)) #建立連線
-
message = 'GET / HTTP/1.1rnrn'
-
s.sendall(message) #傳送GET請求
-
r = s.recv(4096) #接收資料
-
print r
-
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;">
-
HTTP/1.1 302 Moved Temporarily
-
Date: Wed, 10 Jan 2018 18:56:45 GMT
-
Content-Type: text/html
-
Content-Length: 225
-
Connection: Keep-Alive
-
Location: http://www.baidu.com/search/error.html
-
Server: BWS/1.1
-
X-UA-Compatible: IE=Edge,chrome=1
-
BDPAGETYPE: 3
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
import sys
-
HOST = ''
-
PORT = 8088
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
s.bind((HOST, PORT))
-
s.listen(5)
-
print '開始監聽'
-
conn, addr = s.accept
-
print 'Connected with ' + addr[0] + ':' + str(addr[1])
-
data = conn.recv(1024)
-
conn.sendall(data)
-
conn.close
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
host = 'localhost'
-
port = 8088
-
s.connect((host, port)) #建立連線
-
message = 'GET / HTTP/1.1rnrn'
-
s.sendall(message) #傳送GET請求
-
r = s.recv(4096) #接收資料
-
print r
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
import sys
-
HOST = ''
-
PORT = 8088
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
s.bind((HOST, PORT))
-
s.listen(5)
-
print '開始監聽'
-
while True:
-
conn, addr = s.accept
-
print 'Connected with ' + addr[0] + ':' + str(addr[1])
-
data = conn.recv(1024)
-
conn.sendall(data)
-
conn.close
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
import threading
-
HOST = ''
-
PORT = 8088
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
s.bind((HOST, PORT))
-
s.listen(5)
-
print '開始監聽'
-
def runThread(conn):
-
data = conn.recv(1024)
-
print data
-
conn.sendall(data)
-
conn.close
-
while True:
-
conn, addr = s.accept
-
print 'Connected with ' + addr[0] + ':' + str(addr[1])
-
t = threading.Thread(target=runThread, args=(conn,))
-
t.daemon = True
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
import time
-
import threading
-
def run:
-
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
host = 'localhost'
-
port = 8088
-
s.connect((host, port))
-
message = 'GET / HTTP/1.1rnrn'
-
s.sendall(message)
-
print s.recv(4096)
-
s.close
-
if __name__ == '__main__':
-
for i in xrange(4):
-
t = threading.Thread(target=run)
-
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;">
-
開始監聽
-
Connected with 127.0.0.1:61772
-
GET / HTTP/1.1
-
Connected with 127.0.0.1:61773
-
GET / HTTP/1.1
-
Connected with 127.0.0.1:61774
-
GET / HTTP/1.1
-
Connected with 127.0.0.1:61775
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-
s.bind(('', 10000))
-
while True:
-
data, addr = s.recvfrom(1024)
-
print '接收到%s的連線'%str(addr)
-
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;">
-
# -*- coding: utf-8 -*-
-
import socket
-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-
s.sendto('Hello World', ('localhost', 10000))
-
r, addr = s.recvfrom(1024)
-
print r
-
s.close
</pre>