在Python中通过TCP套接字发送文件

Swa*_*rla 37 python sockets tcp file python-2.7

我已经成功地将文件内容(图像)复制到新文件中.但是,当我在TCP套接字上尝试相同的事情时,我遇到了问题.服务器循环未退出.客户端循环在到达EOF时退出,但服务器无法识别EOF.

这是代码:

服务器

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
s.bind((host, port))        # Bind to the port
f = open('torecv.png','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Receiving..."
    l = c.recv(1024)
    while (l):
        print "Receiving..."
        f.write(l)
        l = c.recv(1024)
    f.close()
    print "Done Receiving"
    c.send('Thank you for connecting')
    c.close()                # Close the connection
Run Code Online (Sandbox Code Playgroud)

客户

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.

s.connect((host, port))
s.send("Hello server!")
f = open('tosend.png','rb')
print 'Sending...'
l = f.read(1024)
while (l):
    print 'Sending...'
    s.send(l)
    l = f.read(1024)
f.close()
print "Done Sending"
print s.recv(1024)
s.close                     # Close the socket when done
Run Code Online (Sandbox Code Playgroud)

这是截图:

服务器 服务器

客户 客户

编辑1:复制的额外数据.使文件"不完整".第一列显示已收到的图像.它似乎比发送的更大.因此,我无法打开图像.它似乎是一个损坏的文件.

文件大小

编辑2:这是我在控制台中的操作方式.这里的文件大小相同. Python控制台 文件大小相同

fal*_*tru 29

客户端需要通知它已完成发送,使用socket.shutdown(不是socket.close关闭套接字的读/写部分):

...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
Run Code Online (Sandbox Code Playgroud)

UPDATE

客户端发送Hello server!到服务器; 写入服务器端的文件.

s.send("Hello server!")
Run Code Online (Sandbox Code Playgroud)

删除上面的行以避免它.

  • @SwaathiK,啊,客户端在完成发送后正在等待数据.我更新了答案.请检查一下. (2认同)

Ram*_*hna 5

删除下面的代码

s.send("Hello server!")
Run Code Online (Sandbox Code Playgroud)

因为你发送s.send("Hello server!")到服务器,所以你的输出文件有点大.