############################################################ ## ## TCP Server Socket - By Fischetti P. ## ############################################################ ## ## Serve + client ## ma il client deve inviare la string 'quit' o 'close' o 'q' ## per chiudere la connessione e permettere ## ad altri di continuare. ## inviare 'stop' per terminare il programma ## ############################################################ import socket import time def strTohex(s): lst = [] for ch in s: hv = hex(ord(ch)) lst.append(hv) return lst TCP_IP = '192.168.1.150'#'127.0.0.1' #Per connessioni remote mettere l'IP TCP_PORT = 6000 #Controllare che la porta sia 'opened' con nmap BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) buff=[] bStop=False while 1: print ('Waiting connection on ',socket.gethostname(),TCP_IP,TCP_PORT) conn, addr = s.accept() print ('Connection address:', addr) bContinue=True while bContinue: data = conn.recv(BUFFER_SIZE) if not data: break print ("received data:", data) conn.send(data) # echo sData = data.decode("utf-8").rstrip('\n') #NB o uso b'...' oppure converto in Unicode if data==b'quit\n' or sData=='close' or sData=='q': bContinue = False print ('Connection address:', addr, ' Closed') if sData=='stop' or sData=='x': bContinue = False bStop=True print ('Connection address:', addr, ' Closed') ## ## #TELNET char ## if len(data)==2 and data[0]=='\r' and data[1]=='\n': ## if ''.join(buff).lower()=='close': ## bContinue=False ## print ('Connection address:', addr, ' Closed') ## buff=[] ## else: ## buff.append(data) conn.close() if bStop == True: print("Server Stopped. Bye!") break