Send big file over socket

2020-07-25 05:07发布

问题:

I have a video file and want to send it over socket. Video is send to the client but video is not playable and also video size received is 2 KB. And acutely video size is 43 MB. What is the problem?

Server:

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))

client:

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()

回答1:

Check the return value of send and recv. The 9000000 value is a maximum but not guaranteed value to send/recv. Alternatively, use sendall.

For recv, you have to loop until you receive all the data. If you close the socket after the file is sent, recv will return zero when all the data is received.

FYI, your while True: in both files never loops due to the break, so they are unnecessary.

Here's something that should work...

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.")