C/S架构的简单文件传输系统的实现
源码链接:
https://github.com/GYgavin/python/blob/master/client.py
https://github.com/GYgavin/python/blob/master/server.py
设计思路:
- 确定协议
- 语言选择
- 设计函数
- 构建连接
- 发送文件
选择使用python的原因:
所需实现的功能比较简单,灵活性不需要太高,这样的程序用c语言编写起来太过于繁琐,用python代码量少,容易理解和修改。
实现思路:
1. Server端实现思路
**备注:此处判断的结果yes和no分别代表判断得到客户端的get和put指令
2. Client端实现思路
备注:此处判断yes为put,no为get
实现代码:
服务端代码
#!/usr/bin/env python
from socket import *
import time
HOST = '127.0.0.1'
PORT = 9036
BUFSIZ = 1024000
ADDR = (HOST,PORT)
def recv_file(filename):
print 'Starting receive file...'
filename = open(filename,'wb')
tcpCliSock.send('File will be received!')
while True:
data = tcpCliSock.recv(4096000)
if data == 'EOF':
print 'File received successfully!'
break
filename.write(data)
filename.close()
def send_file(filename):
print 'Starting send file...'
tcpCliSock.send('File will be sent...')
filename = open(filename,'rb')
while True:
data = filename.read(4096000)
if not data:
break
tcpCliSock.send(data)
filename.close()
time.sleep(1)
tcpCliSock.send('EOF')
print 'send file success!'
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock,addr = tcpSerSock.accept()
print('Tcpserver have connected with :',addr)
while True:
command = tcpCliSock.recv(4096000)
act,filename = command.split()
if act == 'put':
print 'receiving file from client,please waiting...'
recv_file(filename)
elif act == 'get':
print 'sending file to client,please waiting...'
send_file(filename)
else:
print 'Error:no command,please input put or get + filename'
continue
客户端代码
#!/usr/bin/env python
import socket
import time
HOST = '127.0.0.1'
PORT = 9036
BUFSIZ = 1024000
ADDR = (HOST,PORT)
tcpCliSock =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def recv_file(filename):
print 'transfer from:',ADDR
filename = open(filename,'wb')
while True:
data = tcpCliSock.recv(4096)
if data == 'EOF':
print 'File received successfully!'
break
filename.write(data)
filename.close
def send_file(filename):
print 'transfer from:',ADDR
filename = open(filename,'rb')
while True:
data = tcpCliSock.recv(4096000)
if data == 'EOF':
print 'File received successfully!'
break
filename.write(data)
filename.close
def send_file(filename):
filename = open(filename,'rb')
while True:
data = filename.read(4096000)
if not data:
break
tcpCliSock.send(data)
filename.close()
time.sleep(1)
tcpCliSock.send('EOF')
print 'send file success!'
try:
tcpCliSock.connect(ADDR)
while True:
client_command = raw_input('File transfer >>')
if not client_command:
continue
tcpCliSock.send(client_command)
act,filename = client_command.split()
if act == 'put':
print 'File sending...'
send_file(filename)
elif act == 'get':
print 'File receiving...'
recv_file(filename)
else:
print 'command error!'
except socket.error,e:
print 'ERROR',e
finally:
tcpCliSock.close()
运行结果:
小编能力有限,水平不高,感谢大家支持,关注!