使用select()的Python TCP服务器

2024-03-29 06:04:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个条目@stackoverflow;-)

我需要一个python3tcp服务器,它将客户机的所有输入发送给其他参与者。服务器正常工作,但不幸的是消息只返回到发送客户端。一旦第二个客户机发送了一些东西,它就得到了全部条目。The因此,在输出队列中可以使用条目。在

为什么select()无法识别条目?在

Thx表示支持。在

`

import select
import socket
import sys
import queue

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)

server_address = ('192.168.100.28', 8888)
print ("starting up on %s port %s" % server_address)
server.bind(server_address)

server.listen(5)

inputs = [ server ]
outputs = [ ]
message_queues = {}




while inputs:
    print ("\nwaiting for the next event")
    readable, writable, exceptional = select.select(inputs, outputs, inputs)

处理输入

^{pr2}$

处理输出

for s in writable:
    try:
        next_msg = message_queues[s].get_nowait()
    except queue.Empty:
        # No messages waiting so stop checking for writability.
        print ("output queue for", s.getpeername(), "is empty")
        outputs.remove(s)
    else:
        print ('sending "%s" to %s' % (next_msg, s.getpeername()))
        s.send(next_msg)

处理“特殊情况”

for s in exceptional:
    print ("handling exceptional condition for", s.getpeername())
    # Stop listening for input on the connection
    inputs.remove(s)
    if s in outputs:
        outputs.remove(s)
    s.close()

    # Remove message queue
    del message_queues[s]

`


Tags: importmessageforserverqueueaddress条目socket
1条回答
网友
1楼 · 发布于 2024-03-29 06:04:45

您的问题是,当您从output列表中读取内容时,您只向其中添加一个对等方。相反,应该在向消息队列写入某些内容时执行此操作。在

接收部分应为:

        ...
        data = s.recv(1024)
        if data:
            # A readable client socket has data
            print ('received "%s" from %s' % (data, s.getpeername()))
            # Add output channel for response
            #message_queues[s].put(data)
            # if s not in outputs:
            #    outputs.append(s)
            for aQueue in message_queues:
                message_queues[aQueue].put(data)
                if aQueue not in outputs:       # enqueue the msg
                    outputs.append(aQueue)      # and ask select to warn when it can be sent
                # AQueue.send ("Test".encode())
        else:
            ...

根据您自己的要求,您应该只为其他参与者排队:

^{pr2}$

最后,您经常测试outputs中是否存在套接字。这让我们认为setlist更合适。在

相关问题 更多 >