我有一个简单的Syslog接收器,以Windows服务启动。服务开始很好......但是当我点击“停止服务”时我无法阻止它。我确定这是因为我被绑定了一个套接字。但是,我无法弄清楚如何从SvcStop函数解除绑定到套接字。有人有主意吗?
OUTPUT_LOG_FILE = 'C:\temp\output.log'
HOST = "192.168.X.X"
PORT = 514
import SocketServer
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "Simple Syslog Receiver"
_svc_display_name_ = "Simple Syslog Receiver"
server = ""
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
try:
global server
server = SocketServer.UDPServer((HOST, PORT), SyslogUDPHandler)
server.serve_forever(poll_interval=0.5)
except (IOError, SystemExit):
raise
pass
class SyslogUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = bytes.decode(self.request[0].strip())
with open(OUTPUT_LOG_FILE, 'w+') as outputfile:
outputfile.write(str(data))
outputfile.close()
if __name__ == "__main__":
win32serviceutil.HandleCommandLine(AppServerSvc)
答案 0 :(得分:0)
Windows 7 + VirtualBox上的相同问题。
我唯一的解决方案是删除此特定端口在VirtualBox中转发,或使用新端口。
即使是基本示例中的标准套接字服务器代码也具有此功能: 它永远运行 2.您无法在Windows进程中看到它 3.虽然Python应用程序已关闭,但它不是“因为它受限于套接字”,因为它继续正确地重放。
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 80
BUFFER_SIZE = 20
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data) # echo
conn.close()
s.close()
raw_input()