简体   繁体   English

通过套接字关闭服务器时通知客户端

[英]Notify client when closing server via socket

I'm creating a socket program.我正在创建一个套接字程序。 The server is always listening to client request and send a response.服务器始终监听客户端请求并发送响应。 When user click button in GUI, the client will send a request to server.当用户在 GUI 中单击按钮时,客户端将向服务器发送请求。

My problem is I want to notify the client that server has been closed when I click close button in GUI in server.我的问题是当我单击服务器中 GUI 中的关闭按钮时,我想通知客户端服务器已关闭。 I have come up with an idea that create a new connection to client always listen to server, but I think it is wasting resources.我想出了一个想法,即创建与客户端的新连接总是监听服务器,但我认为这是在浪费资源。

server.py

while True:
    try:
        request = client.recv(BUFSIZE).decode('utf-8')
    except ConnectionResetError:
        logging.info(str(client.getsockname()) + ' has exited')
        break
    except Exception as e:
        continue
    if request:
        try:
            request = json.loads(request)
            response = self.__handle_request(request, client).encode()
            client.send(response)

client.py

# when user client button
sock.send(request)
response = sock.recv().decode()
render(response)

The client socket IS notified when the server socket closes.当服务器套接字关闭时,会通知客户端套接字。 Your client's sock.recv call will return a zero-length packet, the only instance in which it does so.您的客户端的sock.recv调用将返回一个长度为零的数据包,这是它这样做的唯一实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM