python 套接字 : how to detect that client has closed/disconnected from the server side

标签 python sockets

我有一个小型服务器端程序,它接受来自客户端的连接并写入套接字。我想在客户端断开连接时立即从服务器端进行检测。我看到客户端在断开连接时发送了 TCP Fin,并且服务器仅在有一些数据要向客户端发送时才检测到它,并且我看到管道损坏异常。相反,我希望服务器能够检测到客户端已发送完成并立即关闭 session 。有人可以通过提供一些意见来帮助我吗?

>>> Error sending data: [Errno 32] Broken pipe
[DEBUG] (Keepalive-Thread) Exiting

接受连接的服务器程序:

def enable_pce(ip):
  #Step 1: Create a TCP/IP socket to listen on. This listens for IPv4 AFI
  srv = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

  #Step 2: Prevent from "address in use" upon server restart
  srv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

  #Step 3: Bind the socket to you server ip address

  srv_address = (ip,55555)
  print 'starting server on %s port %s' % srv_address
  srv.bind(srv_address)

  #Step 4: Listen for connections
  srv.listen(1)

  #Step 5: Wait for incoming connections

  connection, peer_address = peer.accept()
  print 'connection from', connection.getpeername()
  return connection

最佳答案

the server is detecting it only when it has some data to send towards the client and I see Broken pipe exception.

可以通过在写入套接字时收到错误(管道损坏)或通过从套接字读取但没有返回任何内容(无错误,无数据)来检测对等方的连接关闭。

在大多数情况下,只有在想要与对等方(读或写)通信时才需要检测断开连接。如果您想在不实际读取或写入数据的情况下执行此操作,您可以使用 select.select 检查套接字的可读性,并使用 recv 查看套接字是否可读。和MSG_PEEK

关于python 套接字 : how to detect that client has closed/disconnected from the server side,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018799/

相关文章:

python - Pandas 数据框 : selecting max by column for subset

python - 我的功能没有运行

scala - Akka scala-io 询问并等待响应

c - linux在c中跨线程连接到相同的sockaddr

database - 在 LAN 上跨 PC 的两个应用程序之间交换数据

python - 使用 2D 数组进行 2D Numpy 数组索引

python - 我如何从 Python 脚本中知道 Python 可执行文件的位置?

python - 为什么仅在带有 python 3.5 的 Jupyter notebook 中给出 SyntaxError : invalid syntax with async def?

Php 套接字、Apache 和 CentOS 6.3 给出权限被拒绝

jakarta-ee - 如何在 Java EE 中创建一个应用程序来监听 TCP/IP 套接字上的传入请求?