我已经成功地将文件内容(图像)复制到一个新文件中。但是,当我通过 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
截图如下:
服务器
客户
编辑 1:复制了额外的数据。使文件“不完整”。 第一列显示已收到的图像。它似乎比发送的要大。因此,我无法打开图像。这似乎是一个损坏的文件。
编辑 2:这就是我在控制台中的操作方式。这里的文件大小是一样的。
最佳答案
客户端需要通知它完成发送,使用 socket.shutdown
(不是 socket.close
关闭套接字的读/写部分):
...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
更新
客户端向服务器发送Hello server!
;写入到服务器端的文件中。
s.send("Hello server!")
删除上面的行以避免它。
关于python - 在 Python 中通过 TCP 套接字发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27241804/