python之socket运用之传输大文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之socket运用之传输大文件相关的知识,希望对你有一定的参考价值。

socket建议最大的传输单元是8192个字符,但是如果超过8192就会出现问题,我们可以用下面的方法处理

客户端代码

import subprocess
import socket
ip_bind = ("127.0.0.1",9000)
client = socket.socket()
client.connect(ip_bind)
l1 = []
while True:
    option = input("client:")
    client.sendall(bytes(option,encoding="utf-8"))
    server_data_size = client.recv(50)
    print(server_data_size)
    a = str(server_data_size,encoding="utf-8").strip()
    print(a)
    l1 = a.split(":")
    print(l1)
    if l1[0] == "server_data_size":
        client_size_tmp = l1[1]
        print(client_size_tmp)
        client_size = int(client_size_tmp)
        print(type(client_size))
    client.send(bytes("ok",encoding="utf-8"))
    receive_size = 0
    res = ""
    while receive_size < client_size:
        server_data = client.recv(100)
        receive_size += len(server_data)
        res += str(server_data)
    else:
        print(res)
        print("-------reveive down---------")

 

 

服务端代码

import subprocess
import socket
ip_bind = ("127.0.0.1",9000)
server = socket.socket()
server.bind(ip_bind)
server.listen(1)
print("server is waiting........")
conn,add = server.accept()
print("server is connected client")
while True:
    client_data = conn.recv(50)
    a = subprocess.Popen(str(client_data,encoding="utf-8"),stdout=subprocess.PIPE)
    b = a.stdout.read()
    server_data_size = "server_data_size:" + str(len(b))
    conn.sendall(bytes(server_data_size,encoding="utf-8"))
    client_ack = conn.recv(10)
    if str(client_ack,encoding="utf-8") == "ok":
        conn.sendall(b)

  

以上是关于python之socket运用之传输大文件的主要内容,如果未能解决你的问题,请参考以下文章

python之socket运用1

Python 之 Socket编程(TCP/UDP)

Python socket之tftp协议

python之网络编程(概述及SOCKET)

Python 之 SSH实例(可接受大字节返回)

python之网络编程