使用select()来监听tcp和udp消息

时间:2011-03-01 22:06:50

标签: python sockets select tcp udp

我在尝试此代码时只收到TCP消息:

from socket import *
from select import select

def read_tcp(s):
    while True:
        client,addr = s.accept()
        data = client.recv(8000)
        client.close()
        print "Recv TCP:'%s'" % data

def read_udp(s):
    while True:
        data,addr = s.recvfrom(8000)
        print "Recv UDP:'%s'" % data

def run():
    host = ''
    port = 8888
    size = 8000
    backlog = 5

    # create tcp socket
    tcp = socket(AF_INET, SOCK_STREAM)
    tcp.bind(('',port))
    tcp.listen(backlog)

    # create udp socket
    udp = socket(AF_INET, SOCK_DGRAM)
    udp.bind(('',port))

    input = [tcp,udp]

    while True:
        inputready,outputready,exceptready = select(input,[],[])

        for s in inputready:
            if s == tcp:
                read_tcp(s)
            elif s == udp:
                read_udp(s)
            else:
                print "unknown socket:", s

if __name__ == '__main__':
    run()

客户端是这样的:

from socket import *

def send_tcp():
    s = socket(AF_INET,SOCK_STREAM)
    s.connect(('localhost',8888))
    data="TCP "*4
    s.send(data)
    s.close()

def send_udp():
    s = socket(AF_INET,SOCK_DGRAM)
    data="UDP "*4
    s.sendto(data, ('localhost',8888))
    s.close()

if __name__ == '__main__':
    send_tcp()
    send_udp()

1 个答案:

答案 0 :(得分:5)

  1. 摆脱read_tcp()和read_udp()中的'while'循环。 select()循环是您需要的唯一循环:它将根据需要经常调用read_XXX()方法。 read_XXX()方法应该只处理一个事件。

  2. 您的read_tcp()方法应分为两部分:一部分接受套接字并将其添加到选择集,另一部分读取接受的套接字。相应地调整选择循环。