- import win32service
- import win32serviceutil
- import win32event
-
- class PySvc(win32serviceutil.ServiceFramework):
- # you can NET START/STOP the service by the following name
- _svc_name_ = "PySvc"
- # this text shows up as the service name in the Service
- # Control Manager (SCM)
- _svc_display_name_ = "Python Test Service"
- # this text shows up as the description in the SCM
- _svc_description_ = "This service writes stuff to a file"
-
- def __init__(self, args):
- win32serviceutil.ServiceFramework.__init__(self,args)
- # create an event to listen for stop requests on
- self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
-
- # core logic of the service
- def SvcDoRun(self):
- import servicemanager
-
- f = open('test.dat', 'w+')
- rc = None
-
- # if the stop event hasn't been fired keep looping
- while rc != win32event.WAIT_OBJECT_0:
- f.write('TEST DATA\n')
- f.flush()
- # block for 5 seconds and listen for a stop event
- rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
-
- f.write('SHUTTING DOWN\n')
- f.close()
-
- # called when we're being shut down
- def SvcStop(self):
- # tell the SCM we're shutting down
- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
- # fire the stop event
- win32event.SetEvent(self.hWaitStop)
-
- if __name__ == '__main__':
- win32serviceutil.HandleCommandLine(PySvc)
import socketimport os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Criado socket do servidorsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)sock.bind(("",1212)) #Fica escutando qualquer IP que fale na porta 1616sock.listen(10) #Escuta ate 10 conexoes simultaneaswhile 1: print " " print "------------------" print "Esperando comando: " conn,addr= sock.accept() msg='1' while msg != "": msg = conn.recv(1024) #Recebe uma mensagem pelo socket aberto, recebe ate 1024 bytes #print "Mensagem recebida -> %s" %(msg) if msg.find("CMD1")!=-1: print 'Comando 1' os.system('echo Comando 1 > c:\\teste.txt') break if msg.find("CMD2") != -1: print 'Comando 2' os.system('echo Comando 2 > c:\\teste.txt') break if msg.find("CMD3") != -1: print 'Comando 3' os.system('echo Comando 3 > c:\\teste.txt') break conn.close()sock.close()
Outro coisa que não entendi foi a parte "# block for 5 seconds and listen for a stop event", o que ele faz ali? trava o programa por 5seg para ver se tem um sinal de parada? se for isso mesmo, iria me atrapalhar e muito, pois vai que alguem envie um comando para o meu programa nesses 5 seg, ai o programa não recebe e não executa o comando.Poderia me explicar melhor?