search
HomeBackend DevelopmentPython Tutorialpython: socket transfer large file example

本篇文章主要介绍了python:socket传输大文件示例,具有一定的参考价值,有兴趣的可以了解一下,

文件可以传输,但是对比传输前后的文件:socket_test.txt,末尾有一些不一致服务端代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import time
'''
等待连接
等待发送文件
读取数据
写入文件并且保存
等待连接
'''
import socket
import threading
import time
import struct


def function(newsock, address):
  FILEINFO_SIZE = struct.calcsize('128sI')
  '''定义文件信息(包含文件名和文件大小)大小。128s代表128个char[](文件名),I代表一个integer or long(文件大小)'''
  while 1:
    try:
      fhead = newsock.recv(FILEINFO_SIZE)
      filename, filesize = struct.unpack('128sI', fhead)
      '''把接收到的数据库进行解包,按照打包规则128sI'''
      print "address is: ", address
      print filename, len(filename), type(filename)
      print filesize
      #filename = 'new_'+filename.strip('\00') # 命名新文件new_传送的文件
      filename = filename.strip('\00')
      fp = open(filename, 'wb') # 新建文件,并且准备写入
      restsize = filesize
      print "recving..."
      while 1:
        if restsize > 102400: # 如果剩余数据包大于1024,就去1024的数据包
          filedata = newsock.recv(10240)
        else:
          filedata = newsock.recv(restsize)
          fp.write(filedata)
          #break
        if not filedata:
          break
        fp.write(filedata)
        restsize = restsize - len(filedata) # 计算剩余数据包大小
        if restsize <= 0:
          break
      fp.close()
      print "recv succeeded !!File named:", filename
    except Exception, e:
      print unicode(e).encode(&#39;gbk&#39;)
      print "the socket partner maybe closed"
      newsock.close()
      break
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建tcp连接
sock.bind((&#39;10.240.146.82&#39;, 8887)) # 定于端口和ip
sock.listen(5) # 监听
while True:
  newsock, address = sock.accept()
  print "accept another connection"
  tmpThread = threading.Thread(target=function, args=(newsock, address)) # 如果接收到文件,创建线程
  tmpThread.start() # 执行线程
print &#39;end&#39;

客户端代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
&#39;&#39;&#39;
输入文件名,并且上传
&#39;&#39;&#39;
import socket
import time
import struct
import os
f = open(&#39;socket_test.txt&#39;, &#39;wb&#39;)

for i in range(1000000):
  f.write(&#39;for socket test, the line number is : &#39; + str(i) + &#39;\n&#39;)

f.close()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(50)
e = 0
try:
  sock.connect((&#39;10.240.146.82&#39;, 8887))
  print &#39;connect...&#39;
except socket.timeout, e:
  print &#39;timeout&#39;, e
except socket.error, e:
  print &#39;error&#39;, e
except e:
  print &#39;any&#39;, e
if not e:
  #while (1):
    #filename = raw_input(&#39;input your filename------->&#39;) # 输入文件名
  filename = &#39;socket_test.txt&#39;
  FILEINFO_SIZE = struct.calcsize(&#39;128sI&#39;) # 编码格式大小
  fhead = struct.pack(&#39;128sI&#39;, filename, os.stat(filename).st_size) # 按照规则进行打包
  sock.send(fhead) # 发送文件基本信息数据
  fp = open(filename, &#39;rb&#39;)
  fp2 = open(&#39;local_test.txt&#39;,&#39;wb&#39;)
  i = 0
  while 1: # 发送文件
    filedata = fp.read(10240)
    if not filedata:
      break
    sock.sendall(filedata)
    fp2.write(filedata)
    print i
    i = i + 1
  print "sending over..."
  fp.close()
  fp2.close()

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多python:socket传输大文件示例相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software