Socket.close()没有关闭Socket

时间:2016-07-19 11:04:48

标签: python sockets client-server

我正在尝试开发一个非常简单的客户端/服务器程序,服务器部分工作正常,但我遇到了客户端部分的问题,但我无法理解原因。

客户端的工作非常简单,只需从外部设备中检索计数器值,然后我就会尝试将检索到的数据发送到服务器部分。

一开始套接字工作正常,但有一段时间我应该发送数据我得到了服务器异常,之后客户端无法正常工作。

我无法理解s.close()函数是否正常工作。

更新:我得到的例外是" errno 110连接超时"

客户端:

   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)

服务器:

  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()

0 个答案:

没有答案