啊峰哥

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)

 

posted on 2017-09-29 13:58  啊峰哥  阅读(196)  评论(0编辑  收藏  举报

导航