我已经成功地将文件内容(图像)复制到新文件。然而,当我通过 TCP 套接字尝试同样的事情时,我遇到了问题。服务器循环未退出。客户端循环在到达 EOF 时退出,但服务器无法识别 EOF。
这是代码:
Server
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
Client
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:复制额外的数据。使文件“不完整”。
第一列显示已收到的图像。好像比寄来的要大一些。因此,我无法打开图像。这似乎是一个损坏的文件。
Edit 2: This is how I do it in the console. The file sizes are the same here.
客户端需要通知它已完成发送,使用socket.shutdown https://docs.python.org/2/library/socket.html#socket.socket.shutdown (not socket.close https://docs.python.org/2/library/socket.html#socket.socket.close关闭套接字的读/写部分):
...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
UPDATE
客户端发送Hello server!
到服务器;它被写入服务器端的文件中。
s.send("Hello server!")
删除上面的线以避免它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)