python⽤socket中的TCPIP协议来传输⽂件
python能够⽤socket来模拟FTP模式传输⽂件,只需在客户端指明需要传输的⽂件名和地址,便能够实现⽂件传输,代码如下:
服务器端:
#-*- coding:ut f-8 -*-
"""
__author__ = BlingBling
建⽴TCP的基本流程
ss = socket() # 创建服务器套接字
ss.bind() # 套接字与地址绑定
ss.listen() # 监听连接
inf_loop: # 服务器⽆限循环
cs = ss.accept() # 接受客户端连接
comm_loop: # 通信循环
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 ')
tcpCliSock, addr = tcpSerSock.accept()
print ('...connected from:', addr)
while True:
data = v(BUFSIZ)
print("recv:",data.decode("utf-8"))
if not data:
break
filename = data.decode("utf-8")
if ists(filename):
filesize = str(size(filename))
print("⽂件⼤⼩为:",filesize)
tcpCliSock.de())
data = v(BUFSIZ) #挂起服务器发送,确保客户端单独收到⽂件⼤⼩数据,避免粘包
print("开始发送")
f = open(filename, "rb")
for line in f:
tcpCliSock.send(line)
else:
tcpCliSock.send("0001".encode()) #如果⽂件不存在,那么就返回该代码
tcpCliSock.close()
tcpSerSock.close()
客户端,接收⽂件:
#-*- 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)
while True:
tcpip协议pdfmessage = input('> ')
if not message:
break
tcpCliSock.send(bytes(message, 'utf-8'))
data = v(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 = v(BUFSIZ)
f.write(data)
received_size += len(data)
print("已接收:",received_size)
f.close()
print("receive done",file_total_size,"",received_size)
tcpCliSock.close()
该代码只是在最后通过⽐较两个⽂件的⼤⼩来判断⽂件是否传输完毕,可以考虑在传输完之后⽐较两个⽂件的MD5值来判断两个⽂件是否⼀样;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论