Python3 socket同步通信簡單示例
本文實例講述了Python3 socket同步通信。分享給大家供大家參考,具體如下:
本文比較簡單,適合入門用,作個筆記,方便日后抄寫
一個服務端,一個客戶端,而且是阻塞方式,一次只能接受一個客戶端連接并通信噢。
客戶端發(fā)送‘bye', 結(jié)束與服務端的通信,如果發(fā)送'shutdown',服務端將會關(guān)閉自己!
服務端代碼:
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()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python轉(zhuǎn)為C語言并編譯生成二進制文件的教程詳解
這篇文章主要為大家詳細介紹了將Python轉(zhuǎn)為C語言并編譯生成二進制文件的相關(guān)教程,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-12-12
python 實現(xiàn)list或string按指定分段
今天小編就為大家分享一篇python 實現(xiàn)list或string按指定分段,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
使用PySpark實現(xiàn)數(shù)據(jù)清洗與JSON格式轉(zhuǎn)換的實踐詳解
在大數(shù)據(jù)處理中,PySpark?提供了強大的工具來處理海量數(shù)據(jù),特別是在數(shù)據(jù)清洗和轉(zhuǎn)換方面,本文將介紹如何使用?PySpark?進行數(shù)據(jù)清洗,并將數(shù)據(jù)格式轉(zhuǎn)換為?JSON?格式的實踐,感興趣的可以了解下2023-12-12
Python3網(wǎng)絡(luò)爬蟲之使用User Agent和代理IP隱藏身份
這篇文章主要介紹了Python3網(wǎng)絡(luò)爬蟲之使用User Agent和代理IP隱藏身份,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
python selenium實現(xiàn)發(fā)送帶附件的郵件代碼實例
這篇文章主要介紹了python selenium實現(xiàn)發(fā)送帶附件的郵件代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12

