|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Senior Member
Iscritto dal: Aug 2008
Città: Firenze
Messaggi: 317
|
[Python] Server in ascolto/timeout
Ciao a tutti! Sto iniziando ad avvicinarmi alla programmazione di rete in Python e volevo qualche consiglio
Server Code: Codice:
'''
Created on 22/ott/2012
@author: Lorenzo
'''
from SocketServer import ThreadingMixIn, TCPServer, BaseRequestHandler
import threading
import sys
import time
class ServerPingPong(ThreadingMixIn, TCPServer):
""" Server TCP Multithread """
start = time.time()
class PingPongHandler(BaseRequestHandler):
""" Handler """
def handle(self):
data = self.request.recv(1024)
if(data == "ping"):
data = "pong"
elif(data == "quit"):
data = "by"
else:
data = "Unknown response"
currThread = threading.current_thread()
response = "{0}: {1}".format(currThread, data)
self.request.sendall(response)
def finish(self):
ServerPingPong.start = time.time()
if __name__ == "__main__":
HOST, PORT = 'localhost', int(sys.argv[1])
server = ServerPingPong((HOST, PORT), PingPongHandler)
ip, port = server.server_address
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
print "Server ready"
while True:
currTime = time.time()
if (currTime - server.start) > 10:
server.shutdown()
break
Codice:
'''
Created on 22/ott/2012
@author: Lorenzo
'''
import socket
import sys
class Client():
""" Client """
def __init__(self, ip, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((ip, port))
def run(self, message):
print "Client message: " + message
try:
self.sock.sendall(message)
response = self.sock.recv(1024)
print "Received response: {0}".format(response)
finally:
self.sock.close()
if __name__ == "__main__":
ip , port = str(sys.argv[1]), int(sys.argv[2])
client = Client(ip, port)
client.run(str(sys.argv[3]))
Ecco la domanda: Come posso gestire il timeout del server in maniera più elegante? Volevo fare qualcosa del genere(ora come ora funziona ma non mi sembra il massimo il server si avvia e rimane in ascolto per 10 secondi: - se riceve una richiesta allora resetta il timer così da rimanere in ascolto per altri 10 secondi - se non riceve richieste termina Grazie mille!!! |
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Jan 2002
Città: Germania
Messaggi: 26110
|
Puoi usare un Timer.
__________________
Per iniziare a programmare c'è solo Python con questo o quest'altro (più avanzato) libro @LinkedIn Non parlo in alcun modo a nome dell'azienda per la quale lavoro Ho poco tempo per frequentare il forum; eventualmente, contattatemi in PVT o nel mio sito. Fanboys |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 23:40.



















