python使用socket實(shí)現(xiàn)的傳輸demo示例【基于TCP協(xié)議】
本文實(shí)例講述了python使用socket實(shí)現(xiàn)的傳輸demo。分享給大家供大家參考,具體如下:
socket傳輸,客戶端代碼
import socket
def main():
tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 服務(wù)器位于本機(jī) 9999
tcp_client_socket.connect( ("192.168.27.72", 9999) )
# 告訴服務(wù)器,我要下載哪一個(gè)文件
file_name = input("請(qǐng)輸入要下載的文件名:")
tcp_client_socket.send(file_name.encode("utf-8"))
temp = tcp_client_socket.recv(1024)
print(temp)
file_length = int(temp.decode("utf-8"))
# 接收數(shù)據(jù) 字節(jié)
recv_data = tcp_client_socket.recv(file_length)
# 得到數(shù)據(jù),需要將數(shù)據(jù)寫入文件
if recv_data:
# f = open("new_" + file_name, "wb")
# try:
# f.write(recv_data)
# except Exception as result:
# print("寫入文件錯(cuò)誤")
# finally:
# f.close()
with open("new_" + file_name, "wb") as f:
f.write(recv_data)
tcp_client_socket.close()
if __name__ == '__main__':
main()
服務(wù)端代碼:
import socket
def main():
#1創(chuàng)建套接字
tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#2綁定本地信息bind
tcp_server_socket.bind(('',9999))
#3讓默認(rèn)的套接字由主動(dòng)變?yōu)楸粍?dòng)listen ????
tcp_server_socket.listen(128)
#4等待別人的電話到來(等待客戶端的鏈接 accept)
new_client_socket, client_addr = tcp_server_socket.accept()
#5調(diào)用發(fā)送文件函數(shù),完成為客戶端服務(wù)
rece_data = new_client_socket.recv(1024)
file_name = rece_data.decode('utf-8')
try:
f = open(file_name, 'rb')
content = f.read()
file_length = len(content)
print(file_length)
new_client_socket.send(str(file_length).encode('utf-8')) #????1兩個(gè)發(fā)送第二個(gè)執(zhí)行快了怎么辦?
new_client_socket.send(content)
except Exception as f:
print('文件打開失敗')
# 6關(guān)閉套接字
new_client_socket.close()
tcp_server_socket.close()
if __name__ == '__main__':
main()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
教你用Python實(shí)現(xiàn)Excel表格處理
今天教各位小伙伴怎么用Python處理excel,文中有非常詳細(xì)的代碼示例及相關(guān)知識(shí)總結(jié),對(duì)正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
jupyter notebook 參數(shù)傳遞給shell命令行實(shí)例
這篇文章主要介紹了jupyter notebook 參數(shù)傳遞給shell命令行實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04
python實(shí)現(xiàn)的AES雙向?qū)ΨQ加密解密與用法分析
這篇文章主要介紹了python實(shí)現(xiàn)的AES雙向?qū)ΨQ加密解密與用法,簡單分析了AES加密解密算法的基本概念并結(jié)合實(shí)例形式給出了AES加密解密算法的相關(guān)實(shí)現(xiàn)技巧與使用注意事項(xiàng),需要的朋友可以參考下2017-05-05
python統(tǒng)計(jì)中文字符數(shù)量的兩種方法
今天小編就為大家分享一篇python統(tǒng)計(jì)中文字符數(shù)量的兩種方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python3.4用循環(huán)往mysql5.7中寫數(shù)據(jù)并輸出的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄猵ython3.4用循環(huán)往mysql5.7中寫數(shù)據(jù)并輸出的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
利用Python代碼實(shí)現(xiàn)一鍵摳背景功能
這篇文章主要給大家介紹了關(guān)于如何利用Python代碼實(shí)現(xiàn)一鍵摳背景的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

