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

2024-04-25 19:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我已成功地将文件内容(图像)复制到新文件中。然而,当我在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

客户

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

这是截图:

服务器Server

客户Client

编辑1:复制额外数据。使文件“不完整” 第一列显示已接收的图像。好像比派来的还大。因为这个,我无法打开图像。好像是个损坏的文件。

File sizes

编辑2:这是我在控制台中的操作方法。这里的文件大小是一样的。 Python ConsoleSame file sizes


Tags: 文件the图像服务器sendhostforclose
3条回答

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

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

更新

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

s.send("Hello server!")

移除上面的线以避免它。

问题是server.py在开始时接收的额外13字节。在while循环之前两次写入“l=c.recv(1024)”进行解析,如下所示。

print "Receiving..."
l = c.recv(1024) #this receives 13 bytes which is corrupting the data
l = c.recv(1024) # Now actual data starts receiving
while (l):

这解决了这个问题,尝试使用不同格式和大小的文件。如果有人知道这个开头的13字节是什么意思,请回复。

删除下面的代码

s.send("Hello server!")

因为您正在将s.send("Hello server!")发送到服务器,所以输出文件的大小稍大一些。

相关问题 更多 >