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

查看:213
本文介绍了通过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

这是屏幕截图:

服务器

客户

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

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.

这是我在控制台中执行的操作.文件大小在这里是相同的.

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

推荐答案

客户端需要使用 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天全站免登陆