這篇文章主要介紹了Python3 socket同步通訊功能,結合簡單實例形式分析了Python socket同步通訊客戶端與伺服器端實作技巧,需要的朋友可以參考下
本文實例講述了Python3 socket同步通訊。分享給大家供大家參考,具體如下:
本文比較簡單,適合入門用,作個筆記,方便日後抄寫
一個服務端,一個客戶端,而且是阻塞方式,一次只能接受一個客戶端連線並通訊噢。
客戶端發送‘bye', 結束與服務端的通信,如果發送'shutdown',服務端將會關閉自己!
服務端程式碼:
from socket import * from time import ctime HOST = '' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) quit = False shutdown = False while True: print('waiting for connection...') tcpCliSock, addr = tcpSerSock.accept() print('...connected from: ', addr) while True: data = tcpCliSock.recv(BUFSIZE) data = data.decode('utf8') if not data: break ss = '[%s] %s' %(ctime(), data) tcpCliSock.send(ss.encode('utf8')) print(ss) if data == 'bye': quit = True break elif data == 'shutdown': shutdown = True break print('Bye-bye: [%s: %d]' %(addr[0], addr[1])) tcpCliSock.close() if shutdown: break tcpSerSock.close() print('Server has been
客戶端程式碼:
from socket import * HOST = 'localhost' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = input('>') if not data: continue print('input data: [%s]' %data) tcpCliSock.send(data.encode('utf8')) rdata = tcpCliSock.recv(BUFSIZE) if not rdata: break print(rdata.decode('utf8')) if data == 'bye' or data == 'shutdown': break tcpCliSock.close()
以上是Python3中socket實現同步通訊的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!