小編給大家分享一下python創(chuàng)建TCP服務(wù)端和客戶端的方法,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

python創(chuàng)建tcp服務(wù)端和客戶端的具體代碼,具體內(nèi)容如下
1.服務(wù)端server
from socket import *
from time import ctime
HOST = ''
PORT = 9999
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM) #創(chuàng)建套接字
tcpSerSock.bind(ADDR) #綁定IP和端口
tcpSerSock.listen(5) #監(jiān)聽端口,最多5人排隊(duì)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept() #建立連接
print('...connected from:', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
content = '[%s] %s' % (bytes(ctime(), "utf-8"), data)
print(data)
print(type(content))
tcpCliSock.send(content.encode("utf-8"))
tcpCliSock.close()
tcpSerSock.close()2.客戶端client
from socket import *
HOST = '127.0.0.1' # or 'localhost'
PORT = 9999
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data.encode("utf-8"))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode("utf-8"))
tcpCliSock.close()看完了這篇文章,相信你對“python創(chuàng)建TCP服務(wù)端和客戶端的方法”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
分享文章:python創(chuàng)建TCP服務(wù)端和客戶端的方法-創(chuàng)新互聯(lián)
網(wǎng)站地址:http://chinadenli.net/article36/dghesg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、定制開發(fā)、手機(jī)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、外貿(mào)網(wǎng)站建設(shè)、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容