当前位置: 首页>>代码示例>>Python>>正文


Python UDPServer.serve_forever方法代码示例

本文整理汇总了Python中SocketServer.UDPServer.serve_forever方法的典型用法代码示例。如果您正苦于以下问题:Python UDPServer.serve_forever方法的具体用法?Python UDPServer.serve_forever怎么用?Python UDPServer.serve_forever使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SocketServer.UDPServer的用法示例。


在下文中一共展示了UDPServer.serve_forever方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __receiver_thread

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
class ALPSUDPConnection:
    def __receiver_thread(self, request, client_address, server):
        message = request[0]
        if callable(self.receiver_func_callback):
            self.receiver_func_callback(self, client_address, message)
            # print client_address

    def __init__(self, ip, port, receiver_func=None, background=False, use_threading=True):
        self.ip_string = ip
        self.port = port
        self.receiver_func_callback = receiver_func
        self.background = background
        if use_threading:
            self.udpconnection = ThreadingUDPServer((self.ip_string, self.port), self.__receiver_thread)
        else:
            self.udpconnection = UDPServer((self.ip_string, self.port), self.__receiver_thread)
        self.udpconnection.allow_reuse_address = True
        # self.__objname = inspect.stack()[1][-2][0].split('=')[0].strip()

    def __serve_forever(self):
        try:
            self.udpconnection.serve_forever()
        except:
            pass

    def bind(self, thread_name="UDPConnection Thread"):
        self.udpsock_thread = ALPSThread(threadfunc=self.__serve_forever, threadname=thread_name)
        self.udpsock_thread.setDaemon(not self.background)
        self.udpsock_thread.start()

    def send(self, client_address, message, error_except=True):
        if type(client_address) is tuple:
            addr_tuple = client_address
        else:
            addr_tuple = (client_address.split(':')[0], int(client_address.split(':')[1]))

        if not error_except:
            return self.udpconnection.socket.sendto(message, addr_tuple)

        try:
            self.udpconnection.socket.sendto(message, addr_tuple)
        except Exception as e:
            ALPSDebug.alps_error(e, '\n', inspect.getframeinfo((inspect.currentframe().f_back)))
            return False
        return True

    def close(self):
        self.udpconnection.server_close()
开发者ID:peterwyj,项目名称:WSDT,代码行数:50,代码来源:ALPSUDP.py

示例2: test

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
    def test(self, selftest):
        # We need to discover SERVEP_IP and set up SERVER_PORT
        # Note: Port 7 is Echo Protocol:
        #
        # Port number rationale:
        #
        # The Echo Protocol is a service in the Internet Protocol Suite defined
        # in RFC 862. It was originally proposed for testing and measurement
        # of round-trip times[citation needed] in IP networks.
        #
        # A host may connect to a server that supports the Echo Protocol using
        # the Transmission Control Protocol (TCP) or the User Datagram Protocol
        # (UDP) on the well-known port number 7. The server sends back an
        # identical copy of the data it received.
        SERVER_IP = str(socket.gethostbyname(socket.getfqdn()))
        SERVER_PORT = 7

        # Returning none will suppress host test from printing success code
        server = UDPServer((SERVER_IP, SERVER_PORT), UDPEchoClient_Handler)
        print("HOST: Listening for UDP connections...")
        self.send_server_ip_port(selftest, SERVER_IP, SERVER_PORT)
        server.serve_forever()
开发者ID:sg-,项目名称:mbed-os,代码行数:24,代码来源:udpecho_client_auto.py

示例3: UDPEchoClientTest

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
class UDPEchoClientTest(BaseHostTest):

    def __init__(self):
        """
        Initialise test parameters.

        :return:
        """
        BaseHostTest.__init__(self)
        self.SERVER_IP = None # Will be determined after knowing the target IP
        self.SERVER_PORT = 0  # Let TCPServer choose an arbitrary port
        self.server = None
        self.server_thread = None
        self.target_ip = None

    @staticmethod
    def find_interface_to_target_addr(target_ip):
        """
        Finds IP address of the interface through which it is connected to the target.

        :return:
        """
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect((target_ip, 0)) # Target IP, Any port
        ip = s.getsockname()[0]
        s.close()
        return ip

    def setup_udp_server(self):
        """
        sets up a UDP server for target to connect and send test data.

        :return:
        """
        # !NOTE: There should mechanism to assert in the host test
        if self.SERVER_IP is None:
            self.log("setup_udp_server() called before determining server IP!")
            self.notify_complete(False)

        # Returning none will suppress host test from printing success code
        self.server = UDPServer((self.SERVER_IP, self.SERVER_PORT), UDPEchoClientHandler)
        ip, port = self.server.server_address
        self.SERVER_PORT = port
        self.server.allow_reuse_address = True
        self.log("HOST: Listening for UDP packets: " + self.SERVER_IP + ":" + str(self.SERVER_PORT))
        self.server_thread = Thread(target=UDPEchoClientTest.server_thread_func, args=(self,))
        self.server_thread.start()

    @staticmethod
    def server_thread_func(this):
        """
        Thread function to run TCP server forever.

        :param this:
        :return:
        """
        this.server.serve_forever()

    @event_callback("target_ip")
    def _callback_target_ip(self, key, value, timestamp):
        """
        Callback to handle reception of target's IP address.

        :param key:
        :param value:
        :param timestamp:
        :return:
        """
        self.target_ip = value
        self.SERVER_IP = self.find_interface_to_target_addr(self.target_ip)
        self.setup_udp_server()

    @event_callback("host_ip")
    def _callback_host_ip(self, key, value, timestamp):
        """
        Callback for request for host IP Addr

        """
        self.send_kv("host_ip", self.SERVER_IP)

    @event_callback("host_port")
    def _callback_host_port(self, key, value, timestamp):
        """
        Callback for request for host port
        """
        self.send_kv("host_port", self.SERVER_PORT)

    def teardown(self):
        if self.server:
            self.server.shutdown()
            self.server_thread.join()
开发者ID:AlessandroA,项目名称:mbed,代码行数:93,代码来源:udp_echo_client.py

示例4: udp_packet_recv

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
def udp_packet_recv(threadName, server_ip, server_port):
    """ This function will receive packet stream from mbed device
    """
    server = UDPServer((server_ip, server_port), UDPEchoClient_Handler)
    print "[UDP_COUNTER] Listening for connections... %s:%d"% (server_ip, server_port)
    server.serve_forever()
开发者ID:AsamQi,项目名称:mbed,代码行数:8,代码来源:udp_link_layer_auto.py

示例5: serve_forever

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
 def serve_forever(self):
     self.start_notifications()
     UDPServer.serve_forever(self)
开发者ID:stereohead,项目名称:pynplay,代码行数:5,代码来源:ssdpserver.py

示例6: __init__

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
class DPM:
    """
        DPM is Data Processing Module
        DPM is used to receive data from routes
        and preprocesses the data and then sends it to WCM and PAM
    """
    def __init__(self, interval):
        """
            init the DPM
            :param interval: the time interval of sending data (ms)
            :return:
        """
        self.__interval = interval / 1000.0
        self.__ip = socket.gethostbyname(socket.gethostname())
        self.__udpServer = UDPServer(('0.0.0.0', DPM_PORT), DataRecvServer)

    def start(self):
        """
            start running the DPM
            :return:
        """
        thSend = Thread(target=self.runSend)
        self.__needQuit = False
        thSend.daemon = True
        thSend.start()
        self.__udpServer.serve_forever()

        try:
            thSend.join()
        except KeyboardInterrupt:
            self.quit()

    def runSend(self):
        """
            Send data to the WCM
            :return:
        """
        while not self.__needQuit:
            sleep(self.__interval)
            with lock:
                body = json.dumps(dataDict)
                header = struct.pack('>BIxxxxI', DPM_MES_TYPE, int(time()), len(body))

                print int(time()), body
                """
                    send data to WCM
                """
                try:
                    WCMSender = TcpClient('0.0.0.0', WCM_PORT)
                    WCMSender.connect()
                    WCMSender.write(header)
                    WCMSender.write(body.encode('utf-8'))
                    WCMSender.flush()
                except:
                    print 'conncect WCM failed'
                finally:
                    WCMSender.close()

                dataDict.clear()

    def quit(self):
        """
            quit the deamon
            :return:
        """
        self.__needQuit = True
        self.__udpServer.shutdown()
开发者ID:edward9210,项目名称:wifi_perceive,代码行数:69,代码来源:dpm.py

示例7: MyRequestHandler

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
#!/usr/bin/env python
#server

from SocketServer import DatagramRequestHandler as DRH, UDPServer as UDP

class MyRequestHandler(DRH):
    def handle(self):
        print "I am server and recved: %s from %s" % (self.rfile.readline(), self.client_address)
        self.wfile.write("I am server")
ss = UDP(('localhost', 9527), MyRequestHandler)
ss.serve_forever()
开发者ID:crazy-canux,项目名称:pythonAPI,代码行数:13,代码来源:ssudpserver.py

示例8: run

# 需要导入模块: from SocketServer import UDPServer [as 别名]
# 或者: from SocketServer.UDPServer import serve_forever [as 别名]
 def run(self):
     addr = ("", PORT)
     log("UDP server listening on : " + str(addr), "debug")
     server = UDPServer(addr, Handler)
     server.serve_forever()
开发者ID:red-ip,项目名称:spot,代码行数:7,代码来源:udpserver.py


注:本文中的SocketServer.UDPServer.serve_forever方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。