1. 程式人生 > 實用技巧 >python用socket中的TCP\IP協議來傳輸檔案

python用socket中的TCP\IP協議來傳輸檔案

server
#-*- coding:utf-8 -*-
"""
__author__ = BlingBling
建立TCP的基本流程
ss = socket() # 建立伺服器套接字
ss.bind() # 套接字與地址繫結
ss.listen() # 監聽連線
inf_loop: # 伺服器無限迴圈
    cs = ss.accept() # 接受客戶端連線
    comm_loop: # 通訊迴圈
        cs.recv()/cs.send() # 對話(接收/傳送)
    cs.close() # 關閉客戶端套接字
ss.close() # 關閉伺服器套接字#(可選)
""" #!/usr/bin/env python import os from socket import * from time import ctime HOST = '' #對bind()方法的標識,表示可以使用任何可用的地址 PORT = 21567 #設定埠 BUFSIZ = 1024 #設定快取區的大小 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) #定義了一個套接字 tcpSerSock.bind(ADDR) #繫結地址 tcpSerSock.listen(5) #規定傳入連線請求的最大數,非同步的時候適用
while True: print('waiting for connection...') tcpCliSock, addr = tcpSerSock.accept() print ('...connected from:', addr) while True: data = tcpCliSock.recv(BUFSIZ) print("recv:",data.decode("utf-8")) if not data: break filename = data.decode("
utf-8") if os.path.exists(filename): filesize = str(os.path.getsize(filename)) print("檔案大小為:",filesize) tcpCliSock.send(filesize.encode()) data = tcpCliSock.recv(BUFSIZ) #掛起伺服器傳送,確保客戶端單獨收到檔案大小資料,避免粘包 print("開始傳送") f = open(filename, "rb") for line in f: tcpCliSock.send(line) else: tcpCliSock.send("0001".encode()) #如果檔案不存在,那麼就返回該程式碼 tcpCliSock.close() tcpSerSock.close()
Client
#-*- coding:utf-8 -*-
"""
__author__ = BlingBling
"""
#!/usr/bin/env python
 
 
from socket import *
 
 
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
 
 
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
 
 
while True:
    message = input('> ')
    if not message:
        break
    tcpCliSock.send(bytes(message, 'utf-8'))
    data = tcpCliSock.recv(BUFSIZ)
    if not data:
        break
    if data.decode() == "0001":
        print("Sorr file %s not found"%message)
    else:
        tcpCliSock.send("File size received".encode())
        file_total_size = int(data.decode())
        received_size = 0
        f = open("new" + message  ,"wb")
        while received_size < file_total_size:
            data = tcpCliSock.recv(BUFSIZ)
            f.write(data)
            received_size += len(data)
            print("已接收:",received_size)
        f.close()
        print("receive done",file_total_size," ",received_size)
tcpCliSock.close()