如何知道客户端在套接字中断开服务器连接 [英] how to know that clients disconnects server in socket

查看:38
本文介绍了如何知道客户端在套接字中断开服务器连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事套接字编程,我必须跟踪所有加入服务器的客户端.

I am working on socket programming and I have to keep the track of all the clients that join the server.

所以我只是给他们一个清单:

So I am just keeping them an list:

client = []

并在客户端连接到服务器时将其附加到它.现在,每当客户端断开连接时,我都必须从列表中删除客户端.问题是服务器如何知道客户端是否已与该服务器断开连接.

and appending the client to it whenever they connect to the server. Now, I have to remove the client from the list whenever the client disconnects. The trouble is how can a server know if a client has disconnected from that server.

对于连接服务器,我使用:

For connecting server, I am using:

s = socket.socket()
s.bind((host, port))
client = []
while True:
   c, addr = s.accept()
   client.append(addr)
s.close()

推荐答案

通常,当套接字断开连接时,如果写入,它会引发 socket.error,并返回 b"" 读取时.

Normally, when a socket is disconnected, it raises a socket.error if written to, and also returns b"" when read from.

所以您可以做的是,您可以捕获该异常并在写入时删除客户端,并在读取时检查数据是否为空.

So what you can do is, you can catch that exception and remove the client if writing to, and check if the data is empty if reading from.

顺便说一句,您需要使用套接字作为客户端,而不是它的地址.

Btw, you need to use the socket as the client, not its addr.

像这样:

try:
    sock.send(data)
except socket.error:
    client.remove(sock)

data = sock.receive(1024)
if not data:
    sock.close()
    client.remove(sock)

这篇关于如何知道客户端在套接字中断开服务器连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆