python - 如何检测服务器正在关闭UNIX域套接字?

标签 python sockets twisted unix-socket

我在弄乱python扭曲的库,而且似乎无法弄清楚如何让我的客户端检测关闭其套接字的服务器。我的客户端继续让我将数据发送到不存在的服务器。这是我的服务器:
test_server.py

from twisted.internet import protocol, reactor, endpoints, stdio
from twisted.protocols.basic import LineReceiver


class ConnectionProtocol(LineReceiver):
    from os import linesep as delimiter

    def lineReceived(self, line):
        print 'got line: %s' % line
        self.sendLine(line)


class ConnectionFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return ConnectionProtocol()


def main():
    endpoint = endpoints.UNIXServerEndpoint(reactor, './test.sock',  5, 0777, False)
    endpoint.listen(ConnectionFactory())
    print 'starting the reactor'
    reactor.run()


main()
它所做的只是将它返回的每一行发送回连接的客户端。
这是客户:
test_client.py
import os
from twisted.internet import protocol, reactor, endpoints, stdio
from twisted.protocols.basic import LineReceiver


class CommandProtocol(protocol.Protocol):
    def dataReceived(self, data):
        print data,


class StdinProtocol(LineReceiver):
    from os import linesep as delimiter

    def __init__(self, client):
        self._client = client

    def connectionMade(self):
        self.transport.write('>>> ')

    def lineReceived(self, line):
        print 'writing line: %s' % line
        self._client.transport.write(line + os.linesep)


def printError(failure):
    print str(failure)


def main():
    point = endpoints.UNIXClientEndpoint(reactor, './test.sock')
    proto = CommandProtocol()
    d = endpoints.connectProtocol(point, proto)
    d.addErrback(printError)

    stdio.StandardIO(StdinProtocol(proto))
    reactor.run()


main()
如果我先运行服务器,然后运行客户端,然后终止服务器,则客户端仍然会像没有任何 react 一样写入CommandProtocol的传输中。我以为errback函数至少会报告一些内容。如果客户端在服务器之前运行,则使用ConnectError调用errback函数,但是我特别希望检测客户端已经连接到服务器并且服务器退出的情况。
如何检测服务器已关闭?

最佳答案

如果在已断开连接的传输上调用,ITransport.write是无提示操作。

如果要了解连接已丢失,请重写connectionLost方法。一旦知道连接已丢失,您可以安排程序停止接受输入或对收到的输入进行其他操作。

关于python - 如何检测服务器正在关闭UNIX域套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213503/

相关文章:

c# - C#套接字: get server when client connects

java - 将消息从 java 发送到 c++,在 c++ 客户端中收到奇怪的东西

python - Python Twisted 中的内存泄漏 : where is it?

python - ValueError 与 TypeError,为什么?

c - 编程 C : getting error when binding address and port to socket

python - 如何使用 python 对单个矩阵值求平方?

python - 扭曲的海螺试验 TDD, "StringTransport instance has no attribute..."

Python Twisted - 服务器通信

python - Pandas date_range 只有小时、分钟和秒

python - 从 JavaCC 源代码生成 Python 语言的解析器?