首页 \ 问答 \ 蟒蛇;(Python; Troubles controlling dead sockets through select)

蟒蛇;(Python; Troubles controlling dead sockets through select)

我有一些代码将连接到主机,除了监听传入的数据,直到客户端关闭或主机发送关闭语句。 为此我的代码运作良好。

但是,当主机在没有发送关闭语句的情况下死亡时,我的客户端会一直按预期继续侦听传入数据。 为了解决这个问题,我每隔foo秒就进行一次套接字超时,并开始检查连接是否存活。 从Python 套接字 howto我发现了这个:

选择的一个非常令人讨厌的问题:如果那些输入列表中的插座中的某个地方已经死了一个令人讨厌的死亡,那么选择将失败。 然后你需要遍历所有这些列表中的每一个该死的套接字并执行select([sock],[],[],0)直到找到坏的套接字。 超时0意味着它不会花费很长时间,但它很难看。

    # Example code written for this question.
    from select import select
    from socket include socket, AF_INET, SOCK_STREAM

    socket = socket(AF_INET, SOCK_STREAM)
    socket.connect(('localhost', 12345))
    socklist = [socket,]
    attempts = 0

    def check_socklist(socks):
        for sock in socklist:
            (r, w, e) = select([sock,], [], [], 0)          

            ...
            ...
            ...

    while True:

        (r, w, e) = select(socklist, [], [], 60)

        for sock in r:      
            if sock is socket:
                msg = sock.recv(4096)
                if not msg:
                    attempts +=1
                    if attempts >= 10:
                        check_socket(socklist)
                    break
                else:
                    attempts = 0
                    print msg

本文提出了三个问题。

  1. 我被教导要检查连接是否存活,必须写入套接字并查看响应是否返回。 如果没有,则必须假设连接已经死亡。 在文中它说要检查错误的连接,每个套接字一个,将它传递给select的第一个参数并将超时设置为零。 这将如何确认插座是否已经死?
  2. 为什么不通过尝试写入套接字来测试套接字是死还是活?
  3. 当连接处于活动状态并且已经死亡时,我在寻找什么? 选择将立即超时,因此没有数据将证明什么。

我意识到像geventasyncoretwisted这样的库可以帮助我解决这个问题,但是我选择这样做是为了更好地理解正在发生的事情,并且能够更好地控制我的源头。


I have some code which will connect to a host and do nothing but listen for incoming data until either the client is shut down or the host send a close statement. For this my code works well.

However when the host dies without sending a close statement, my client keeps listening for incoming data forever as expected. To resolve this I made the socket timeout every foo seconds and start the process of checking if the connection is alive or not. From the Python socket howto I found this:

One very nasty problem with select: if somewhere in those input lists of sockets is one which has died a nasty death, the select will fail. You then need to loop through every single damn socket in all those lists and do a select([sock],[],[],0) until you find the bad one. That timeout of 0 means it won’t take long, but it’s ugly.

    # Example code written for this question.
    from select import select
    from socket include socket, AF_INET, SOCK_STREAM

    socket = socket(AF_INET, SOCK_STREAM)
    socket.connect(('localhost', 12345))
    socklist = [socket,]
    attempts = 0

    def check_socklist(socks):
        for sock in socklist:
            (r, w, e) = select([sock,], [], [], 0)          

            ...
            ...
            ...

    while True:

        (r, w, e) = select(socklist, [], [], 60)

        for sock in r:      
            if sock is socket:
                msg = sock.recv(4096)
                if not msg:
                    attempts +=1
                    if attempts >= 10:
                        check_socket(socklist)
                    break
                else:
                    attempts = 0
                    print msg

This text creates three questions.

  1. I was taught that to check if a connection is alive or not, one has to write to the socket and see if a response returns. If not, the connection has to be assumed it is dead. In the text it says that to check for bad connections, one single out each socket, pass it to select's first parameter and set the timeout to zero. How will this confirm that the socket is dead or not?
  2. Why not test if the socket is dead or alive by trying to write to the socket instead?
  3. What am I looking for when the connection is alive and when it is dead? Select will timeout at once, so having no data there will prove nothing.

I realize there are libraries like gevent, asyncore and twisted that can help me with this, but I have chosen to do this my self to get a better understanding of what is happening and to get more control over the source my self.


原文:https://stackoverflow.com/questions/19795529
更新时间:2023-07-20 19:07

最满意答案

我想你正在考虑modulophp modulo operator % )? 它在执行除法后提供余数。 例如:

师:

10 / 3 = 3.333...

模:

10 % 3 = 1

在编程使用中,您可以使用第一个(除法)操作的楼层来获取完整组的数量,并使用模数来获取最后一组的大小。

例如,如果你以14开头:

3组有多少组?

floor(14 / 3) = 4

最后一组有多少人?

14 % 3 = 2

I think you are thinking of modulo (php modulo operator %)? It provides the remainder after performing division. For example:

Division:

10 / 3 = 3.333...

Modulo:

10 % 3 = 1

In programming use, you can use the floor of the first (division) operation to get the number of full groups, and the modulus to get the size of the last group.

For example, if you start with 14:

How many groups of 3?

floor(14 / 3) = 4

How many in last group?

14 % 3 = 2

相关问答

更多
  • import math x = 1234.5678 math.modf(x) # (0.5678000000000338, 1234.0) Use math.modf: import math x = 1234.5678 math.modf(x) # (0.5678000000000338, 1234.0)
  • 阅读有关记忆的内容 。 关键的见解是,如果你有一个序列从A开始,其长度为1001,然后你得到一个产生A的序列B,你就不要再重复所有这些工作了。 Have a read about memoization. The key insight is that if you've got a sequence starting A that has length 1001, and then you get a sequence B that produces an A, you don't to repeat a ...
  • 这是我的第一次拍摄(来自评论)。 我会编辑这篇文章,因为我会有更好的想法。 算法: Input (a) a list L (b) a number x, the maximum gap 1) Sort the list 2) Take as many elements from the list as you can without exceeding the gap 3) Create a new group 4) If there are no more elements in the list, yo ...
  • 喜欢这个? def split_ranges(amount, max) (0...amount).collect{|i| (i * max / amount)...((i+1) * max / amount)} end p split_ranges(3, 46000000) 输出: [0...15333333, 15333333...30666666, 30666666...46000000] 编辑:(OP请求) def split_ranges(amount, max) (0...a ...
  • 我会这样做: 添加所有值,让我们调用这个S. 将S除以列数,我们称之为M. 使用背包算法(例如http://search.cpan.org/~andale/Algorithm-Knapsack-0.02/lib/Algorithm/Knapsack)找到一组其值为M或尽可能接近M的值。下午 (只是一个快速的谷歌背包)) 取一组值的总和并从S中减去它,我们称之为T. 将T除以列数减1 并重复该算法 I would do it like this: add all the values, let's call ...
  • 我想你正在考虑modulo ( php modulo operator % )? 它在执行除法后提供余数。 例如: 师: 10 / 3 = 3.333... 模: 10 % 3 = 1 在编程使用中,您可以使用第一个(除法)操作的楼层来获取完整组的数量,并使用模数来获取最后一组的大小。 例如,如果你以14开头: 3组有多少组? floor(14 / 3) = 4 最后一组有多少人? 14 % 3 = 2 I think you are thinking of modulo (php modulo o ...
  • 这应该产生你想要的 n = 8202; a = [0:4001:n; [4000:4001:n-1 n]]' 回报 a = 0 4000 4001 8001 8002 8202 This should produce what you want n = 8202; a = [0:4001:n; [4000:4001:n-1 n]]' returns a = 0 4000 ...
  • 这是一个快速的脚本,可能会让你靠近那里: MAXPOINTS = 10 JUNKWORDS={"trouble":6,"solution":5,"charge":3,"virus":7} fil = open("filnamne.txt", "r") foundwords = {} points = 0 for word in fil.read().split(): if word in JUNKWORDS: if word not in foundwords: ...
  • 您需要考虑某种方式将序列转换为相应的组。 我刚才从其他用户那里学到了这个技巧。 通过使用贯穿所有记录的ROW_NUMBER ,您可以通过从该行号中减去同一记录上的value来计算组密钥。 如果values是连续的,则减法结果不会发生变化(因此产生相同的组密钥)。 否则,组密钥将跳转到下一个(较小)值。 每次跳跃时,组密钥都会变小。 这是查询: select min(value) min, max(value) max from (select value, ROW_NUMBER() over (order ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)