說明
前一段時間學習python網絡編程,完成簡單的通過python實現網絡通信的功能。現在,將python中Socket
通信的基本實現過程做一個記錄備份.
Socket通信
python 中的socket通信較爲簡單,僅需要幾行代碼就可實現。和一般的網絡通信一樣,通信方式分爲udp和tcp兩種方式,兩種方式的處理也略有不同。tcp通信爲傳輸控制協議(Transmission control Protocol),是一種面向連接、可靠的、基於字節流的傳輸層通信協議(TCP/IP協議簇劃分的通信協議的其中一層);udp通信爲用戶數據報協議(User Datagram Protocol),是一種面向無連接、不可靠的、基於報文的傳輸層通信協議。就是TCP/IP中的兩種傳輸層通信協議,有關TCP/IP和TCP、UDP的詳細介紹視情況而定看是否需要單獨介紹,由於內容涉及較廣,個人並不能完全完整詳細的介紹仔細。
python網絡通信需要導入一個socket模塊來支持通信過程。socket通信分爲客戶端和服務端。服務端負責監聽當前設備接口的信息發送情況,客戶端實現通過ip和接口向目的主機發送信息的功能。接下來,主要看python中的tcp、udp的通信方法.
1) tcp
服務端代碼如下:
import socket
#socket.AF_INET:ipv4,socket.SOCK_STREAM:tcp
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind((target,port))
server_socket.listen(5)
while True:
client_socket,addr=server_socket.accept()
client_handler=threading.Thread(target=handler_socket,args=(client_socket,addr,mode))
client_handler.start()
def handler_socket(client_socket,addr,mode="tcp"):
response=""
content=""
print "Accepted tcp connection from:%s:%d" % (addr[0],addr[1])
while True:
response=client_socket.recv(2048)
content+=response
while len(response)<2048:
print "content:%s" % content
response=""
content=""
a=raw_input("send to:")
if len(a):
client_socket.send(a)
客戶端代碼:
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((target,port))
a=raw_input("input your text what you want to send:")
if len(a):
client.send(a)
while True:
buffer=""
response=""
a=""
while "\n" not in response:
response=client.recv(2048)
buffer+=response
print "Received buffer:%s" % buffer
a=raw_input("send to server:")
if len(a):
client.send(a)
2) udp
服務段代碼:
#socket.AF_INET:ipv4,socket.SOCK_STREAM:udp
sever_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
server_socket.bind((target,port))
server_socket.listen(5)
while True:
client_socket,addr=server_socket.accept()
client_handler=threading.Thread(target=handler_socket,args=(client_socket,addr,mode))
client_handler.start()
pass
def handler_socket(client_socket,addr,mode="tcp"):
response=""
content=""
print "Accepted udp connection from:%s:%d" % (addr[0],addr[1])
while True:
response=client_socket.recvfrom(2048)
content+=response
while len(response) <2048:
print "content:%s" % content
response=""
content=""
a=raw_input("send to:")
if len(a):
client_socket.sendto(a,addr)
客戶端代碼
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
a=raw_input("input your text what you want to send:")
if len(a):
client.sendto(a,(target,port))
while True:
buffer=""
response=""
a=""
while "" in response:
response,addr=client.recvfrom(4096)
print "Received buffer:%s" % buffer
a=raw_input("send to server:")
if len(a):
client.send(a)
如上爲基本的實現tcp/udp實現socket同學的基礎用法,我寫了一個可選tcp/udp socket通信的的實例代碼在github,源碼地址爲:socket通信