Python套接字,为什么程序会被阻止?

时间:2018-01-29 13:30:00

标签: python sockets

我的程序被屏蔽,客户端从未走出循环,出了什么问题?

'''Client, send hello,world'''

import socket

s = socket.socket()
s.connect(('localhost', 6969))
s.send(b'hello, world')
while True:
    data = s.recv(1024)
    if data:
        print(data)
    else:
        break #never gets here


'''Server, first receive, then send'''
import socket, threading

def tr(sock, addr):
    while True:
        data = sock.recv(1024)
        if data:
            print(data)
        else:
            break #never gets here
    sock.send(b'get it') 
    # sock.close()

s = socket.socket()
s.bind(('localhost', 6969))
s.listen(5)

while True:
    sock, addr = s.accept()
    t = threading.Thread(target=tr,args=(sock, addr))
    t.start()

1 个答案:

答案 0 :(得分:1)

您的客户端挂起是预期的行为,因为没有人启动套接字关闭。 socket.recv()阻止,直到数据可用。如果您的套接字处于活动状态但没有要读取的数据,则不会返回None。

如果您在服务器端的意图是接收消息,然后做某事,返回响应并最终关闭连接,这可行:

def tr(sock, addr):
    while True:
        data = sock.recv(1024)
        if data:
            print(data)
            sock.send(b'get it')
            sock.close()
            break
        else:
            break #never gets here

这将读取消息,发送响应并关闭套接字。现在您的客户端按预期工作。

如果要与服务器和客户端之间来回传递的消息建立更持久的连接,那么您需要在某个时刻触发套接字关闭,然后您的客户端将退出。如果您不这样做,您的客户将假设有更多数据要来recv()等待它可用。