gpt4 book ai didi

python - 通过套接字发送大文件

转载 作者:行者123 更新时间:2023-11-30 21:55:43 24 4
gpt4 key购买 nike

我有一个视频文件,想通过套接字发送它。视频已发送到客户端,但视频无法播放,并且收到的视频大小为 2 KB。准确地说,视频大小为 43 MB。有什么问题吗?

服务器:

import socket

try:

soc = socket.socket()
print('socked created.')
host = ''
port = 8080

soc.bind((host, port))
print('soc bound.')

soc.listen(10)
print('waiting for connecting...')

con, addr = soc.accept()
print('server connected to IP: ' + addr[0] + " port: " + str(addr[1]))

while True:

filename = input('enter filename: ')
file = open(filename, 'rb')
sendfile = file.read(9000000)
con.send(sendfile)
print("file has been send.")
break

con.close()
soc.close()

except socket.error as err:
print('error ', str(err))

客户:

import socket

soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socked created. waiting for connecting to server...')

server_address = ("192.168.1.3", 8080)

soc.connect(server_address)
print('connected to the server.')

while True:
recvfile = soc.recv(9000000)
savefilebyname = input("enter file name: ")
openfile = open(savefilebyname, 'wb')
openfile.write(recvfile)
openfile.close()
break

print("File has been received.")

soc.close()

最佳答案

检查sendrecv的返回值。 9000000 值是一个最大值,但不保证发送/接收的值。或者,使用sendall

对于recv,您必须循环直到收到所有数据。如果在发送文件后关闭套接字,则当接收到所有数据时,recv 将返回零。

仅供引用,两个文件中的 while True: 由于 break 永远不会循环,因此它们是不必要的。

这是应该有用的东西......

server.py

import socket

soc = socket.socket()
soc.bind(('',8080))
soc.listen(1)

print('waiting for connection...')
with soc:
con,addr = soc.accept()
print('server connected to',addr)
with con:
filename = input('enter filename to send: ')
with open(filename, 'rb') as file:
sendfile = file.read()
con.sendall(sendfile)
print('file sent')

client.py

import socket

soc = socket.socket()
soc.connect(('localhost',8080))
savefilename = input("enter file name to receive: ")
with soc,open(savefilename,'wb') as file:
while True:
recvfile = soc.recv(4096)
if not recvfile: break
file.write(recvfile)
print("File has been received.")

关于python - 通过套接字发送大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com