一个功能内有多个端口

时间:2020-05-26 16:36:43

标签: python

rest-utils

我希望我的功能能够连续为我提供两个端口的结果,但是每次只能打印出一个结果。

2 个答案:

答案 0 :(得分:0)

使用线程,如Robert Kearns所述:

import threading
import socket


def port_watcher(port):

    UDP_IP = "127.0.0.1"
    UDP_PORT = port

    print("Binding port: %s" % port)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((UDP_IP, UDP_PORT))

    while True:
        data, addr = sock.recvfrom(1024)
        print("received message:", data)


threads = list()
for port in (44134, 44135):
    x = threading.Thread(target=port_watcher, args=(port,))
    threads.append(x)
    x.start()

输出:

Binding port: 44134
Binding port: 44135

答案 1 :(得分:0)

虽然线程确实起作用,但是您仍然可以使用端口列表在一次while循环中检查两个端口:

import socket

class Port(object):
    def __init__(self, UDP_IP, UDP_PORT):
        self.UDP_IP = UDP_IP
        self.UDP_PORT = UDP_PORT

def port_watcher(ports):
    port_list = []

    #Connect each port
    for port in ports:
        index = len(port_list)
        port_list.append(Port("127.0.0.1", port))

        print("Binding port: %s" % port_list[index].UDP_PORT)
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind((port_list[index].UDP_IP, port_list[index].UDP_PORT))

    while True:
        #Check each port
        for port in port_list:
            data, addr = sock.recvfrom(1024)
            print("received message for port " + port.UDP_PORT  + ":" + data)


port_watcher([4134, 4135]) #You can put as many ports as you want as list elements