我正在尝试在使用Python编写的对等聊天系统中通过TCP套接字发送文件。接收端似乎不知道没有更多的文件需要接收。唯一能让接收端不再预期未到来的数据的方法是关闭发送端套接字(使用socket.shutdown(socket.SHUT_WR))。但是,关闭发送端套接字不是一个选项,因为我需要该套接字发送其他消息。我首先尝试分配新的端口进行文件传输,但失败了。现在,我尝试创建一个文件结尾的“信号”,但接收端未能将其识别为与TCP段分开的消息,因此我陷入困境。
发送代码如下:
接收代码如下所示:
发送代码如下:
def sendFile(self,filePath):
try:
f = open(filePath, 'rb')
print 'file opened'
for soc in self.allClients.keys():
try:
f = open(filePath, 'rb')
except:
print "File does not exist"
print 'Sending File: ' + filePath
l = f.read(1024)
while (l):
print 'Sending...'
soc.send(l)
l = f.read(1024)
soc.send('end')
f.close()
print 'File sent'
except:
print "File does not exist"
接收代码如下所示:
def receiveFile(self, ext, clientsoc):
f = open('receivedFile' + ext,'wb')
print "Receiving File..."
l = clientsoc.recv(1024)
while(l):
print "Receiving..."
if (l is not 'end'):
f.write(l)
print l + '\n'
l = clientsoc.recv(1024)
else:
break
f.close()
print "Received Fileeeeeooooo"
更奇怪的是,当我将此代码用于我的同事程序之外时,它可以正常运行。如果能提供帮助,将不胜感激。我已经为此苦苦挣扎了两天。