我有两个程序,sendfile.py和recvfile.py应该进行交互以通过网络发送文件。它们通过TCP套接字进行通信。通信应该是这样的:
sender =====filename=====> receiver
sender <===== 'ok' ======= receiver
or
sender <===== 'no' ======= receiver
if ok:
sender ====== file ======> receiver
我有
发件人和收件人代码在这里:
发信人:
import sys
from jmm_sockets import *
if len(sys.argv) != 4:
print "Usage:", sys.argv[0], "<host> <port> <filename>"
sys.exit(1)
s = getClientSocket(sys.argv[1], int(sys.argv[2]))
try:
f = open(sys.argv[3])
except IOError, msg:
print "couldn't open file"
sys.exit(1)
# send filename
s.send(sys.argv[3])
# receive 'ok'
buffer = None
response = str()
while 1:
buffer = s.recv(1)
if buffer == '':
break
else:
response = response + buffer
if response == 'ok':
print 'receiver acknowledged receipt of filename'
# send file
s.send(f.read())
elif response == 'no':
print "receiver doesn't want the file"
# cleanup
f.close()
s.close()
接收器:
from jmm_sockets import *
s = getServerSocket(None, 16001)
conn, addr = s.accept()
buffer = None
filename = str()
# receive filename
while 1:
buffer = conn.recv(1)
if buffer == '':
break
else:
filename = filename + buffer
print "sender wants to send", filename, "is that ok?"
user_choice = raw_input("ok/no: ")
if user_choice == 'ok':
# send ok
conn.send('ok')
#receive file
data = str()
while 1:
buffer = conn.recv(1)
if buffer=='':
break
else:
data = data + buffer
print data
else:
conn.send('no')
conn.close()
我确信我在这里遇到了各种各样的僵局,但不知道它是什么。
答案 0 :(得分:3)
使用阻塞套接字,这是默认的,我假设你正在使用(由于你正在使用一个神秘的模块jmm_sockets
而无法确定),recv
方法正在阻塞 - 当它似乎没有“暂时不返回”时,它不会返回一个空字符串,正如你似乎所假设的那样。
你可以解决这个问题,例如,通过发送一个明确的终止符(必须永远不会出现在文件名中),例如'\xff'
,在您要发送的实际字符串之后,在另一端等待它,作为现在已收到所有字符串的指示。
答案 1 :(得分:1)