python - 程序在套接字交互期间挂起

标签 python sockets network-programming communication-protocol

我有两个程序,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()

我确信我在僵局中遗漏了一些东西,但不知道它是什么。

最佳答案

使用阻塞套接字(这是默认设置,我假设您正在使用它(无法确定,因为您使用的是神秘模块jmm_sockets)),recv 方法是阻塞的——当它“暂时没有什么可返回的”时,它不会返回空字符串,正如您所假设的那样。

您可以解决此问题,例如,通过发送显式终止符(绝不能出现在文件名中),例如'\xff',在您要发送的实际字符串之后,并在另一端等待它,表明所有字符串现已收到。

关于python - 程序在套接字交互期间挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2901350/

相关文章:

django - 错误: Invalid HTTP_HOST header: '/webapps/../gunicorn.sock'

sockets - TCP 多连接与 1 连接(应用程序管理)

c++ - 我应该使用哪个 TLS 库,可移植性是个问题

c++ - 如何在 C++ 中创建 UDP 套接字的示例

python - 使用模板自定义 Django FormWizard 步骤

python - 从 Linux 发行版包管理器切换到 Anaconda

python - 通过 Alembic Sc​​eneGraph 重命名 ReadGeo 节点

java - 套接字编程中的代码卡在 readLine() 中

c - 如何在 C 中获取我的非环回网络 ip 地址?

python - 如何在 Dask DataFrame 中创建唯一索引?