python3基于TCP实现CS架构文件传输


Posted in Python onJuly 28, 2018

本文实例为大家分享了python3实现CS架构文件传输的具体代码,供大家参考,具体内容如下

1、目标:

基于tcp实现CS架构的文件传输

指令列表:(1)get:从服务器端下载文件

                    (2)put:向服务器端上传文件

                    (3)list:获得服务器端的目录

2、socket模块函数:

(1)send和sendall:send的作用是发送TCP数据,返回发送的数据大小。send函数不保证将所有数据全部发送,因此可能需要重复多次才能完成所有数据的发送。sendall的作用是发送完整的TCP数据,成功时返回None,失败时抛出异常

(2)bind:在服务器端使用,用于将socket绑定在一个特定的ip地址和端口上。在《UNIX网络编程》一书中提到,如果调用connect或者listen之前没有bind一个特定的端口,内核会为相应的套接字分配一个随机的端口。因此,在客户端调用connect函数之前不需要bind

(3)listen:通过参数设定服务器端最多可以接受几个客户端的连接,但是只有在完成与第一个客户端的传送后才会进行与第二个客户端的传送

3、代码:

(1)服务器端:

import socket 
import os 
import sys 
import time 
 
Host = '127.0.0.1' 
Port = 12000 
Addr = (Host, Port) 
 
sockListener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sockListener.bind(Addr) 
sockListener.listen(5) 
 
def recvfile(cliSocket): 
  print('start reveiving file...') 
  msg = 'no problem' 
  msg_utf8 = msg.encode(encoding="utf-8") 
  cliSocket.send(msg_utf8) 
  filename_utf8 = clientSocket.recv(4096) 
  filename = filename_utf8.decode() 
  f = open(filename, 'wb') 
  while True: 
    data_utf8 = cliSocket.recv(4096) 
    data = data_utf8.decode() 
    if data=='EOF': 
      print('received file successfully') 
      break 
    f.write(data_utf8) 
  f.close() 
 
def sendfile(cliSocket): 
  print('start sending file...') 
  msg = 'no problem' 
  msg_utf8 = msg.encode(encoding="utf-8") 
  cliSocket.send(msg_utf8) 
  filename_utf8 = cliSocket.recv(4096) 
  filename = filename_utf8.decode() 
  f = open(filename, 'rb') 
  while True: 
    data = f.read(4096) 
    if not data: 
      break 
    cliSocket.sendall(data) 
  f.close() 
  time.sleep(1) 
  msg = 'EOF' 
  msg_utf8 = msg.encode(encoding="utf-8") 
  cliSocket.sendall(msg_utf8) 
  print('sent file successfully') 
 
def getList(cliSocket): 
  path = sys.path[0] 
  every_file = os.listdir(path) 
  for filename in every_file: 
    pathmsg = filename + '\n' 
    pathmsg_utf8 = pathmsg.encode(encoding="utf-8") 
    cliSocket.sendall(pathmsg_utf8) 
  time.sleep(1) 
  msg = 'EOF' 
  msg_utf8 = msg.encode(encoding="utf-8") 
  cliSocket.sendall(msg_utf8) 
  print('all filenames have been send') 
 
while True: 
  print('waiting for connection...') 
  clientSocket, addr = sockListener.accept() 
  print('... connection from:', addr) 
 
  while True: 
    msg_utf8 = clientSocket.recv(4096) 
    msg = msg_utf8.decode() 
    if msg=='exit': 
      print(addr, 'close the connection') 
      break 
    elif msg=='get': 
      sendfile(clientSocket) 
    elif msg=='put': 
      recvfile(clientSocket) 
    elif msg=='list': 
      getList(clientSocket) 
    else: 
      print('client error!') 
      break

(2)客户端:

import socket 
import time 
 
Host = '127.0.0.1' 
Port = 12000 
Addr = (Host, Port) 
 
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
clientSocket.connect(Addr) 
 
def recvfile(filename): 
  print('start receiving file...') 
  f = open(filename, 'wb') 
  filename_utf8 = filename.encode(encoding="utf-8") 
  clientSocket.sendall(filename_utf8) 
  while True: 
    data_utf8 = clientSocket.recv(4096) 
    data=data_utf8.decode() 
    if data=='EOF': 
      print('receive file successfully') 
      break 
    f.write(data_utf8) 
  f.close() 
 
def sendfile(filename): 
  print('start sending file...') 
  f = open(filename, 'rb') 
  filename_utf8 = filename.encode(encoding="utf-8") 
  clientSocket.sendall(filename_utf8) 
  while True: 
    data = f.read(4096) 
    if not data: 
      break 
    clientSocket.sendall(data) 
  f.close() 
  time.sleep(1) 
  endmsg = 'EOF' 
  endmsg_utf8 = endmsg.encode(encoding="utf-8") 
  clientSocket.sendall(endmsg_utf8) 
  print('send file successfully') 
 
def confirm(confirm_command): 
  confirm_command_utf8 = confirm_command.encode(encoding="utf-8") 
  clientSocket.sendall(confirm_command_utf8) 
  msg_utf8 = clientSocket.recv(4096) 
  msg = msg_utf8.decode() 
  print('reveive message:', msg) 
  if msg=='no problem': 
    return True 
  else: 
    return False 
 
def operation1(filename): 
  if confirm('get'): 
    recvfile(filename) 
  else: 
    print('serve error!') 
 
def operation2(filename): 
  if confirm('put'): 
    sendfile(filename) 
  else: 
    print('serve error!') 
 
def operation3(act): 
  if act=='list': 
    act_utf8 = act.encode(encoding="utf-8") 
    clientSocket.sendall(act_utf8) 
    while True: 
      msg_utf8 = clientSocket.recv(1024) 
      msg = msg_utf8.decode() 
      if msg=='EOF': 
        break 
      print(msg) 
  else: 
    print('wrong command!') 
try: 
  while True: 
    command = input('>>>') 
    if not command: 
      continue 
    elif command=='exit': 
      command_utf8 = command.encode(encoding="utf-8") 
      clientSocket.sendall(command_utf8) 
      print('the connection is closed') 
      break 
    msg = command.split() 
    if len(msg)==2 and msg[0]=='get': 
      operation1(msg[1]) 
    elif len(msg)==2 and msg[0]=='put': 
      operation2(msg[1]) 
    elif len(msg)==1: 
      operation3(msg[0]) 
    else: 
      print('wrong command!') 
except socket.error as e: 
  print('error:', e) 
  print('an error causes the connection to close!') 
  clientSocket.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python内置的字符串处理函数详细整理(覆盖日常所用)
Aug 19 Python
Python文本处理之按行处理大文件的方法
Apr 09 Python
python3学习之Splash的安装与实例教程
Jul 09 Python
情人节快乐! python绘制漂亮玫瑰
Aug 18 Python
基于Python的PIL库学习详解
May 10 Python
基于python 微信小程序之获取已存在模板消息列表
Aug 05 Python
Python selenium抓取虎牙短视频代码实例
Mar 02 Python
Pycharm中使用git进行合作开发的教程详解
Nov 17 Python
python爬虫scrapy图书分类实例讲解
Nov 23 Python
python爬虫请求头的使用
Dec 01 Python
详解Python调用系统命令的六种方法
Jan 28 Python
python 实现的截屏工具
May 08 Python
python cs架构实现简单文件传输
Mar 20 #Python
Tornado Web Server框架编写简易Python服务器
Jul 28 #Python
python使用tornado实现登录和登出
Jul 28 #Python
基于python实现简单日历
Jul 28 #Python
python使用tcp实现局域网内文件传输
Mar 20 #Python
基于python3实现socket文件传输和校验
Jul 28 #Python
python多进程实现文件下载传输功能
Jul 28 #Python
You might like
便携利器 — TECSUN PL-365简评
2021/03/02 无线电
php后台程序与Javascript的两种交互方式
2009/10/25 PHP
php 模拟POST|GET操作实现代码
2010/07/20 PHP
ThinkPHP自动填充实现无限级分类的方法
2014/08/22 PHP
PHP使用DirectoryIterator显示下拉文件列表的方法
2015/03/13 PHP
php伪静态验证码不显示的解决方案
2019/09/26 PHP
Thinkphp 框架配置操作之配置加载与读取配置实例分析
2020/05/15 PHP
javascript 鼠标拖动图标技术
2010/02/07 Javascript
jQuery实现鼠标点击弹出渐变层的方法
2015/07/09 Javascript
js代码验证手机号码和电话号码是否合法
2015/07/30 Javascript
bootstrap输入框组代码分享
2016/06/07 Javascript
JavaScript中的子窗口与父窗口的互相调用问题
2017/02/08 Javascript
JQuery查找子元素find()和遍历集合each的方法总结
2017/03/07 Javascript
基于JavaScript实现表格滚动分页
2017/11/22 Javascript
微信小程序中时间戳和日期的相互转换问题
2018/07/09 Javascript
代码实例ajax实现点击加载更多数据图片
2018/10/12 Javascript
JS实现的自定义map方法示例
2019/05/17 Javascript
Vue+Element实现动态生成新表单并添加验证功能
2019/05/23 Javascript
Vue打包部署到Nginx时,css样式不生效的解决方式
2020/08/03 Javascript
探究一道价值25k的蚂蚁金服异步串行面试题
2020/08/21 Javascript
在Mac OS上使用mod_wsgi连接Python与Apache服务器
2015/12/24 Python
python 接口返回的json字符串实例
2018/03/27 Python
Python变量赋值的秘密分享
2018/04/03 Python
python获取微信小程序手机号并绑定遇到的坑
2018/11/19 Python
​如何愉快地迁移到 Python 3
2019/04/28 Python
详解Python绘图Turtle库
2019/10/12 Python
win10下python2和python3共存问题解决方法
2019/12/23 Python
动物学专业毕业生求职信
2013/10/11 职场文书
涉外经济法专业毕业生推荐信
2013/11/24 职场文书
国际贸易专业个人求职信范文分享
2013/12/14 职场文书
企业党建工作汇报材料
2014/08/19 职场文书
教师节感恩老师演讲稿
2014/08/28 职场文书
社区灵活就业证明
2014/11/03 职场文书
疾病证明书
2015/06/19 职场文书
2016年综治和平安建设宣传月活动总结
2016/04/01 职场文书
一文解答什么是MySQL的回表
2022/08/05 MySQL