1.5 socket服务器传输文件

socket服务器代码

# -*- coding: utf-8 -*-
import
sys,os,time,_thread from socket import * host = 'localhost' port = 50001 def now(): return time.asctime() def server_thread(conn): sockfile = conn.makefile('r') filename = sockfile.readline()[:-1] try: #读取文件内容,并传输 file = open(filename,'rb') while True: bytes = file.read(1024) if not bytes: break sent = conn.send(bytes) assert sent == len(bytes) except: print('Error downloading file on server:',filename) conn.close() def server(host,port): sock = socket(AF_INET, SOCK_STREAM) sock.bind((host, port)) sock.listen(5) while True: conn,addr = sock.accept() print('Server connect by',addr,'at',now()) _thread.start_new_thread(server_thread,(conn,)) #开启线程 server(host,port)

 

socket客户端代码

# -*- coding: utf-8 -*-
import
sys,os,time,_thread from socket import * host = 'localhost' port = 50001 def now(): return time.asctime() def client(host,port,filename): sock = socket(AF_INET,SOCK_STREAM) sock.connect((host,port)) sock.send((filename + '\n').encode()) dropdir = 'New ' + os.path.split(filename)[1] #获取文件地址,保存在默认目录下 file = open(dropdir,'wb') #创建本地文件 while True: data = sock.recv(1024) if not data: break file.write(data) #储存数据 sock.close() file.close() print('Client got ',filename,'at',now()) filename = input('请输入文件目录,如:testdir\\a.gif') client(host,port,filename)

 

转载于:https://www.cnblogs.com/fg2312/p/7610729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值