无法启动多个套接字监听器

时间:2019-06-27 12:14:53

标签: python sockets server

我做了一个简单的套接字服务器类。在另一个脚本中,我想通过传递一些参数来初始化服务器。

import socket
from pygrok import Grok

class Loghunter:

    # We define some global vars
    buffersize = 1024  #buffersize
    bindaddress = '127.0.0.1' #bindaddress
    server_socket = None; #server instance var
    grok = None; #grok instance var

    # Initialize class loghunter
    def __init__(self, *args):

    # Map params to vars
        bindport = args[0]
        socktype = args[1].upper()
        parsertype = args[2]
        pattern =  args[3]

    # Create server depending on protocol type (UDP, TCP)
        if socktype == 'UDP':
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            print 'UDP server started.'

        elif socktype == 'TCP':
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print 'TCP server started.'

    # Bind server to address and socket
        self.server_socket.bind((self.bindaddress, bindport))

    #self.server_socket.listen(1)

    # Create grok parser and initialize it with pattern
        self.grok = Grok(pattern)

    # While loop is True do some things, like running the function
        while True:

    # Call function to parse message with GROK
            print(self.parsemsg(pattern))

    # Define parser function
    def parsemsg(self, pattern):

    # Get message, address from socket
        message, address = self.server_socket.recvfrom(self.buffersize)
    # Parse message and store it to var
        msg = self.grok.match(message)

    # Return message
        return msg

我也有这个脚本,我在其中创建带有侦听器设置的列表,并循环遍历以生成那些服务器/侦听器。 问题在于它只产生第一个。然后停止。

from loghunter import Loghunter

pattern = '<%{INT:pri}>%{INT} %{TIMESTAMP_ISO8601:date} %{HOSTNAME:host} %{DATA:program} (?:%{INT:pid})? %{GREEDYDATA:message}'

inputs = [ [1234, 'udp', 'grok'],[2321, 'udp', 'cef'],[2222, 'udp', 'cef'] ]
running = []

print(inputs)

for srv in inputs:
    print(srv[0])
    log = Loghunter(srv[0], srv[1], srv[2], pattern)
    running.append(log)

print(running)

这是运行脚本时的样子。

$: python udpserver4.py 
[[1234, 'udp', 'grok'], [2321, 'udp', 'cef'], [2222, 'udp', 'cef']]
1234
UDP server started.

如何实现我想要的?

0 个答案:

没有答案