Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Python - Server/Client Problema con i Socket
Forum - Python - Server/Client Problema con i Socket

Avatar
macco_cl (Normal User)
Rookie


Messaggi: 34
Iscritto: 27/02/2007

Segnala al moderatore
Postato alle 16:04
Mercoledì, 20/07/2016
Ciao a tutti!


Ho sviluppato due semplici Script Server/Client, illustro in breve il funzionamento in modo che sia più chiaro il mio problema:

Il server rimane sempre in ascolto sul socket in attesa che il client gli invii un messaggio, a messaggio ricevuto si deve solo preoccupare di elaborare il messaggio e inserirlo in un DB.

Il client invece si occupa di testare il funzionamento di una porta seriale e di effettuare una lettura da un dispositivo esterno, se i dati che avevo in precedenza sono cambiati rispetto la lettura attuale allora devo inviare tali dati al server tramite socket.

I due script sembrerebbero essere funzionanti, infatti quando lancio il server e successivamente il client i messaggi inviati dal client arrivano correttamente a server, il problema che ho è che se per 2 minuti (o più tempo) il client non invia nessun dato, perché le letture del dispositivo non hanno subito variazioni dallo stato precedete, e improvvisamente ottengo una lettura con un cambiamento, il client si blocca dandomi errore sul socket di tipo timeout.

Premesso che so che il modo migliore per fare un Client/Server che faccia le cose di cui ho bisogno sarebbe necessario usare i thread vi pregherei ugualmente di aiutarmi.

Sto letteralmente impazzendo dietro questo semplice codice, spero che possiate veramente aiutarmi perché non so proprio capire dove sto sbagliando.
:hail::hail::hail::hail::hail:


Server:
Codice sorgente - presumibilmente Python

  1. import socket
  2. import json
  3. import time
  4. import Config_mio
  5. import packet
  6. import sqlite3 as lite
  7.  
  8. if __name__ == "__main__":
  9.     """Main function that starts the server"""
  10.  
  11.     # Creates TCP socket in the specified IP address and port
  12.     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  13.     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  14.     s.bind((Config_mio.IP_Server_Add, Config_mio.ws_port))
  15.  
  16.     # Starts server, up to 10 clients are queued
  17.     s.listen(Config_mio.Max_Num_Clients)
  18.  
  19.     while True:
  20.  
  21.         #try:
  22.  
  23.             con = lite.connect('test.db')
  24.             #print "sono prima di mettermi in ascolto"
  25.             conn, addr = s.accept()
  26.             #print "sono dopo ascolto"
  27.             msg = conn.recv(1024)
  28.             print "Data value:",msg
  29.  
  30.             msg = msg.split(",")
  31.  
  32.             if msg[0] == "c": # msg type identification if request_type is c we have a counter people msg
  33.  
  34.                 print "counter msg"
  35.                 timestamp = msg[1]
  36.                 RbPiId = msg[2]
  37.                 people_in = msg[3]
  38.                 people_out = msg[4]
  39.                 #print  msg[2]
  40.                 #print  msg[3]
  41.                 #print  msg[4]
  42.  
  43.                 with con:
  44.                     cur = con.cursor()
  45.  
  46.  
  47.                     def dataEntry():
  48.  
  49.                             cur.execute("CREATE TABLE IF NOT EXISTS Data_Occupancy (ID, TimeStamp, In_Count, Out_Count)")
  50.                             cur.execute("CREATE TABLE IF NOT EXISTS Dynamic_occupancy (ID TEXT PRIMARY KEY, In_Count, Out_Count, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)")
  51.                             cur.execute("CREATE TABLE IF NOT EXISTS Inertial_Data (Platform_Id, Gyro_X_Axis, Gyro_Y_Axis, Gyro_Z_Axis, Acc_X_Axis, Acc_Y_Axis, Acc_Z_Axis, Magn_X_Axis, Magn_Y_Axis, Magn_Z_Axis, Temperature, Pressure, Humidity, Timestamp)")
  52.                             cur.execute("INSERT INTO Data_Occupancy (ID, TimeStamp, In_Count, Out_Count) VALUES(?, ?, ?, ?)",(RbPiId, timestamp, people_in, people_out))
  53.                             cur.execute("INSERT OR REPLACE INTO Dynamic_Occupancy VALUES (?, ?, ?, CURRENT_TIMESTAMP) ", (RbPiId, people_in, people_out))
  54.                             #cur.execute("DELETE FROM Dynamic_occupancy WHERE  sqltime < datetime('now', '-60 seconds')")
  55.  
  56.  
  57.                             con.commit()
  58.  
  59.  
  60.                 dataEntry()  # Entry data
  61.                 con.close()
  62.  
  63.             elif msg[0] == "r":
  64.  
  65.                 print "range msg",msg[1],msg[2],msg[5]
  66.  
  67.                 timestamp_r = msg[1]
  68.                 RbPiId_r = msg[2]
  69.                 ranging = msg[5]
  70.  
  71.                 with con:
  72.                     cur = con.cursor()
  73.  
  74.                     def dataEntry():
  75.  
  76.                         cur.execute("CREATE TABLE IF NOT EXISTS Inertial_Data (Platform_Id, Gyro_X_Axis, Gyro_Y_Axis, Gyro_Z_Axis, Acc_X_Axis, Acc_Y_Axis, Acc_Z_Axis, Magn_X_Axis, Magn_Y_Axis, Magn_Z_Axis, Temperature, Pressure, Humidity, Timestamp)")
  77.                         cur.execute("CREATE TABLE IF NOT EXISTS Ranging (ID, TimeStamp, Ranging_Data_Meters)")
  78.                         cur.execute("CREATE TABLE IF NOT EXISTS Ranging_Dynamic (ID TEXT PRIMARY KEY , TimeStamp, Ranging_Data_Meters, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)")
  79.                         cur.execute("INSERT OR REPLACE INTO Ranging_Dynamic VALUES (?, ?, ?, CURRENT_TIMESTAMP) ", (RbPiId_r, timestamp_r, ranging))
  80.                         cur.execute("DELETE FROM Ranging_Dynamic WHERE  sqltime < datetime('now', '-1 minutes')")
  81.  
  82.                         con.commit()
  83.  
  84.  
  85.                 dataEntry()  # Entry data
  86.                 con.close()
  87.  
  88.  
  89.         #except:
  90.          #   print "Errore di connessione"
  91.             conn.close()



Client:

Codice sorgente - presumibilmente Python

  1. import time, socket, struct, array, json
  2. import Client_Axis
  3. import sys
  4. import serial
  5. import os
  6. import datetime
  7. import re
  8. import packet
  9. import Config_mio
  10. usbport = '/dev/ttyAMA0'
  11.  
  12. h = "/r/n"
  13.  
  14.  
  15.  
  16. if __name__=="__main__":
  17.     """Main function that starts the server"""
  18.  
  19.     curr_value = "0000000000"
  20.     prev_value = ""
  21.     line = '111111111111111'
  22.     error_counter = 0
  23.     people_in = 0
  24.     people_out = 0
  25.     txtDate = ""
  26.     no_updates_counter = 0
  27.  
  28.     while True:
  29.  
  30.         ser = None
  31.  
  32.         try:
  33.             # print('1')
  34.             ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1)
  35.             # ser.open()
  36.             # print('2')
  37.  
  38.             for line in ser.read():
  39.                 line = ser.readline()
  40.  
  41.             print(line[6:10])
  42.             curr_value = line
  43.  
  44.         except:
  45.  
  46.             print('Serial error')
  47.             # print('3')
  48.             pass
  49.  
  50.         finally:
  51.             if ser:
  52.                 ser.close()
  53.  
  54.         try:
  55.             error_counter += 1
  56.             # print('1')
  57.             response = Client_Axis.Read_Axis_Camera_Occupancy()
  58.             code = response.code
  59.             print "CODE VALUE:",code
  60.             if (code == 200):
  61.                 content = response.read()
  62.                 fields = content.split(",")
  63.  
  64.                 people_in_refresh = int(re.search(r'\d+', fields[3]).group())
  65.                 people_out_refresh = int(re.search(r'\d+', fields[4]).group())
  66.                 # print('2')
  67.                 error_flag = 0
  68.  
  69.                 if people_in != people_in_refresh or people_out != people_out_refresh:
  70.  
  71.                     people_in = people_in_refresh
  72.                     people_out = people_out_refresh
  73.  
  74.                     try:
  75.  
  76.                         # Creates TCP socket in the specified IP address and port
  77.                         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  78.                         # Connect client to the server
  79.                         s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
  80.                         # Create message and send it to server
  81.                         timestamp = str(time.time())
  82.  
  83.                         msg = "c"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+str(people_in)+","+str(people_out)+","+"None"
  84.  
  85.                         s.send(msg)
  86.                         print "sent msg"
  87.  
  88.                     except socket.error, exc:
  89.                         print "Server connection error 1: %s" % exc
  90.                         pass
  91.  
  92.                     finally:
  93.                         s.close()
  94.             else:
  95.                 print "CODE WRONG"
  96.  
  97.  
  98.         except:
  99.             error_msg = "Error retrieving occupancy from: " + Config_mio.IP_AXIS_Add
  100.             error_flag = 1
  101.  
  102.  
  103.         if (error_flag == 1):
  104.             no_updates_counter = 0
  105.             print "Error detected: %s \r\n" % error_msg
  106.             print error_counter
  107.  
  108.             if (error_counter > 200):
  109.                 os.system("sudo reboot")
  110.  
  111.         elif (line[6:10] != '1111' and prev_value != curr_value):
  112.  
  113.             try:
  114.                 # Creates TCP socket in the specified IP address and port
  115.                 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  116.                 # Connect client to the server
  117.                 s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
  118.  
  119.                 timestamp = str(time.time())
  120.  
  121.                 # Create message and send it to server
  122.                 msg = "r"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+"None"+","+"None"+","+str(line[6:10])
  123.  
  124.                 s.send(msg)
  125.                 print "Message : %s" % msg
  126.  
  127.             except socket.error, exc:
  128.                 print "Server connection error 2: %s" % exc
  129.                 pass
  130.  
  131.             finally:
  132.                 s.close()
  133.  
  134.         else:
  135.             no_updates_counter += 1
  136.  
  137.             # Send message despite there are no changes in value
  138.             # This is a heartbeat message of 10 min
  139.             if (no_updates_counter > 200):
  140.                 no_updates_counter = 0
  141.                 AXIS_occup = ""
  142.  
  143.         prev_value = curr_value
  144.  
  145.         # Reboot device every day - routine
  146.         # We have 4 cases incase we miss few seconds
  147.         txtDate = str(datetime.datetime.fromtimestamp(time.time()))
  148.         if (txtDate[11:19] == "00:00:00"):
  149.             os.system("sudo reboot")
  150.         if (txtDate[11:19] == "00:00:01"):
  151.             os.system("sudo reboot")
  152.         if (txtDate[11:19] == "00:00:02"):
  153.             os.system("sudo reboot")
  154.         if (txtDate[11:19] == "00:00:03"):
  155.             os.system("sudo reboot")
  156.         # Kill time - 1 sec: Remove it for high speed localisation
  157.         time.sleep(1)


PM Quote