我有一个视频文件,想通过套接字发送。视频已发送到客户端,但视频无法播放,并且接收到的视频大小为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()
答案 0 :(得分:1)
检查send
和recv
的返回值。 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.")