Python socket網路模組
阿新 • • 發佈:2018-12-15
一、基於TCP協議的socket通訊
以打電話為理解方式進行TCP的通訊。
Server端程式碼: import socket phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #購買電話卡,AF_INET伺服器之間網路通訊,socket.SOCK_STREAM,流式協議,就是TCP協議 phone.bind(('127.0.0.1', 8080)) #選擇電話號碼,繫結IP地址 phone.listen(5) #開機,監控5個請求,最多能進入6個,第7個會報錯 conn, addr= phone.accept() #等待接聽電話,阻塞狀態,獲取IP和埠 print(conn, addr) #列印IP和埠 client_data = conn.recv(1024) #交流過程 print(client_data) #列印接收到的資料 conn.send(client_data.upper()) #接收到的英文字母變成大寫並回傳資料 conn.close() phone.close() Client端程式碼:import socket phone = socket.socket() phone.connect(('127.0.0.1', 8080)) msg = input('>>>').strip() phone.send(msg.encode('utf-8')) server_data = phone.recv(1024) #限制最大接收位元組 print(server_data) phone.close() 先執行Server端,再執行Client端,輸入:Others laugh at me for being mad. I laugh at others for not being able to see through.------------------------------------Client端執行結果--------------------------------------- >>>Others laugh at me for being mad. I laugh at others for not being able to see through. b'OTHERS LAUGH AT ME FOR BEING MAD. I LAUGH AT OTHERS FOR NOT BEING ABLE TO SEE THROUGH.' ------------------------------------------------------------------------------------------ ------------------------------------Server端執行結果---------------------------------------- <socket.socket fd=244, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8080), raddr=('127.0.0.1', 64096)> ('127.0.0.1', 64096) b'Others laugh at me for being mad. I laugh at others for not being able to see through.' -------------------------------------------------------------------------------------------
二、單迴圈模式
Server端程式碼: import socket phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #使用TCP協議建立網路通訊 phone.bind(('127.0.0.1', 8080)) #繫結IP地址和埠 phone.listen(5) #設定最大連線數,但是同一時間只能處理一個請求while 1: #使服務端能夠一直接受資料
conn, addr = phone.accept() #獲取連線到伺服器的IP和埠 try: client_data = conn.recv(1024) #接收1024位元組的資料 print(client_data) #列印資料(數字為bytes型別) conn.send(client_data + b'-yes-') #源資料加上-yes-並返回給客戶端 except Exception: break conn.close() phone.close() Client端程式碼: import socket phone = socket.socket() phone.connect(('127.0.0.1', 8080)) while 1: msg = input('>>>').strip() #可輸入要傳輸的字元 if msg.upper() == 'Q': #如果輸出q則退出
break
elif not msg: #如果msg接到到的內容為空,則結束本次迴圈
continue phone.send(msg.encode('utf-8')) #使用utf-8的編碼進行傳送資料 server_data = phone.recv(1024) #最多隻能接受1024位元組,只問題會產生粘包 print(server_data.decode('utf-8')) #列印解碼後的資料 phone.close() ------------------------------------Client端執行結果--------------------------------------- >>>laugh #輸入要傳到S端的內容 laugh-yes- #打印出來的是S端返回的內容 >>>crazy crazy-yes- >>>q Process finished with exit code 0 -------------------------------------------------------------------------------------------
------------------------------------Server端執行結果----------------------------------------
b'laugh' #收到C端傳送來的內容
b'crazy'
-------------------------------------------------------------------------------------------
三、遠端執行命令