0

I'm trying to develop a very simple client/server program, the server part is working properly but I've a problem with the client part but I can't understand why.

The client's work is very simple, just retrive the counter value from a external device, then I'm trying to send the retrieved data to the server part.

At the beginning the socket is working well, but some time when I should send the data I've got the server exception and after that the Client is not working.

I can't understand if the s.close() function is working properly.

UPDATE: the exception that I got is "errno 110 connection timed out"

Client:

   import time, socket, struct, array, json
   import Client_Axis
   import sys
   import serial
   import os
   import datetime
   import re
   import packet
   import Config_mio
   usbport = '/dev/ttyAMA0'

   h = "/r/n"



   if __name__=="__main__":
"""Main function that starts the server"""

curr_value = "0000000000"
prev_value = ""
line = '111111111111111'
error_counter = 0
people_in = 0
people_out = 0
txtDate = ""
no_updates_counter = 0

while True:

    ser = None

    try:
        # print('1')
        ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1)
        # ser.open()
        # print('2')

        for line in ser.read():
            line = ser.readline()

        print(line[6:10])
        curr_value = line

    except:

        print('Serial error')
        # print('3')
        pass

    finally:
        if ser:
            ser.close()

    try:
        error_counter += 1
        # print('1')
        response = Client_Axis.Read_Axis_Camera_Occupancy()
        content = response.split(",")

        people_in_refresh = int(re.search(r'\d+', content[3]).group())
        people_out_refresh = int(re.search(r'\d+', content[4]).group())
        # print('2')
        error_flag = 0

        if people_in != people_in_refresh or people_out != people_out_refresh:

            people_in = people_in_refresh
            people_out = people_out_refresh

            try:

                # Creates TCP socket in the specified IP address and port
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                # Connect client to the server
                s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
                # Create message and send it to server
                timestamp = str(time.time())

               # msg = packet("c", timestamp, Config_mio.RbPi_Id, content[3], content[4], None)
                msg = "c"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+str(people_in)+","+str(people_out)+","+"None"

                    # json_message = json.dumps(msg)
                    # s.send(json_message)
                s.send(msg)
                print "messaggio INVIATO"

                # Close connection when data is sent
                #s.close()
            except:
                print('Server connection error 1')
                pass

            finally:
                s.close()



                #AXIS_occup_old = AXIS_occup
                #AXIS_occup = response.read()
                #my_dict = json.loads(AXIS_occup)
                # print(AXIS_occup)
                # print(my_dict)
                #del my_dict["timestamp"]
                #AXIS_occup = my_dict
                #error_counter = 0
                # print('3')


    except:
        error_msg = "Error retrieving occupancy from: " + Config_mio.IP_AXIS_Add
        error_flag = 1

    if (error_flag == 1):
        no_updates_counter = 0
        print "Error detected: %s \r\n" % error_msg
        print error_counter

        if (error_counter > 200):
            os.system("sudo reboot")

    elif (line[6:10] != '1111' and prev_value != curr_value):

        try:
            # Creates TCP socket in the specified IP address and port
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # Connect client to the server
            s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))

            # Create message and send it to server
            timestamp = str(time.time())

            msg = "r"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+"None"+","+"None"+","+str(line[6:10])
            #msg = {"Id": raspberry_id,
             #      "Ranging": line[6:10],
              #     "timestamp": timestamp}

            #json_message = json.dumps(msg)
            #s.send(json_message)
            s.send(msg)
            print "Message : %s" % msg

            # Close connection when data is sent
            s.close()
        except:
            print('Server connection error 2')
            pass


    else:
        no_updates_counter += 1

        # Send message despite there are no changes in value
        # This is a heartbeat message of 10 min
        if (no_updates_counter > 200):
            no_updates_counter = 0
            AXIS_occup = ""

    prev_value = curr_value

    # Reboot device every day - routine
    # We have 4 cases incase we miss few seconds
    txtDate = str(datetime.datetime.fromtimestamp(time.time()))
    if (txtDate[11:19] == "00:00:00"):
        os.system("sudo reboot")
    if (txtDate[11:19] == "00:00:01"):
        os.system("sudo reboot")
    if (txtDate[11:19] == "00:00:02"):
        os.system("sudo reboot")
    if (txtDate[11:19] == "00:00:03"):
        os.system("sudo reboot")
    # Kill time - 1 sec: Remove it for high speed localisation
    time.sleep(1)

Server:

  import socket
  import json
  import time
  import Config_mio
  import packet
  import sqlite3 as lite

   if __name__ == "__main__":
"""Main function that starts the server"""

# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((Config_mio.IP_Server_Add, Config_mio.ws_port))

# Starts server, up to 10 clients are queued
s.listen(Config_mio.Max_Num_Clients)

while True:



        conn, addr = s.accept()
        #print "sono dopo ascolto"
        msg = conn.recv(1024)
        print "Data value:",msg

        msg = msg.split(",")

        if msg[0] == "c": 
            print "counter msg"

        elif msg[0] == "r":

            print "range msg",msg[1],msg[2],msg[5]



        conn.close()
macco
  • 21
  • 1
  • 11
  • If you get an exception please add the complete exception with traceback. – syntonym Jul 19 '16 at 11:47
  • Does `s.shutdown(socket.SHUT_RDWR)` before `s.close()` help? This should explain what it does: http://stackoverflow.com/a/38239957/5781248 – J.J. Hakala Jul 21 '16 at 11:52

0 Answers0