在 Python 中通过 TCP 套接字发送文件 [英] Sending a file over TCP sockets in Python

查看:29
本文介绍了在 Python 中通过 TCP 套接字发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've successfully been able to copy the file contents (image) to a new file. However when I try the same thing over TCP sockets I'm facing issues. The server loop is not exiting. The client loop exits when it reaches the EOF, however the server is unable to recognize 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

客户

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

截图如下:

服务器

客户

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

Edit 1: Extra data copied over. Making the file "not complete." The first column shows the image that has been received. It seems to be larger than the one sent. Because of this, I'm not able to open the image. It seems like a corrupted file.

编辑 2:这就是我在控制台中的做法.此处的文件大小相同.

Edit 2: This is how I do it in the console. The file sizes are the same here.

推荐答案

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

Client need to notify that it finished sending, using socket.shutdown (not socket.close which close both reading/writing part of the socket):

...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()

更新

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

Client sends Hello server! to the server; which is written to the file in the server side.

s.send("Hello server!")

删除上面的行以避免它.

Remove above line to avoid it.

这篇关于在 Python 中通过 TCP 套接字发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆