概述
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import json
import socket
import time,datetime
import os
HOST='192.168.0.120'
PORT=8850
BUFFER=9600
#定义socket通信类型 ipv4,tcp
soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#连接服务器
soc.connect((HOST,PORT))
#用函数获取现在时间,用于给消息添加时间戳
def get_time():
now = time.time()
local_time = time.localtime(now)
return time.strftime('%Y-%m-%d %H:%M:%S',local_time)
#获取现在时间,创建带时间戳的目录文件
now = time.time()
local_time = time.localtime(now)
date_filetime =
time.strftime('%Y-%m-%d %H:%M:%S',local_time)
date_doctime =
time.strftime('%Y-%m-%d',local_time)
docname= u'data/'+date_doctime
vehicle_txtname = u'/vehicle_data.txt'
lane_txtname = u'/lane_data.txt'
vehicleFlow_txtname = u'/flow_data.txt'
#如果没有。就创建文件夹
if not os.path.exists(docname):
os.mkdir(docname)
vehicle_file=open(docname+vehicle_txtname,"a+")#打开文件,有就打开,没有就创建
lane_file=open(docname+lane_txtname,"a+")
flow_file=open(docname+vehicleFlow_txtname,"a+")
ipname = ''
vehicle_list = []
counter = 0
def vehicles_done(which):
if which == 0:
for i in range(len(vehicle_list)):
if i == 0:
#print("lane")
#print(len(lane_list))
vehicle_file.write("TimeNow:t"+get_time()+'n')
vehicle_file.write("deviceIP:t"+vehicle_list[0]+'n')
vehicle_file.write("vehicles:tn")
else:
dic_vehi = vehicle_list[i]
vehicle_file.write("carType:ttt"+dic_vehi[u'carType']+'n')
vehicle_file.write("traceId:ttt"+dic_vehi[u'traceId']+'n')
vehicle_file.write('nn')
vehicle_file.flush() #实时更新文件
print(u'print the vehi info! sort1')
return
if which == 1:
#添加内容
return
try:
while 1:
time.sleep(1)
buf=soc.recv(BUFFER)#接收TCP信息
data = json.loads(buf[2:-2])#去掉头尾,将json消息转成字典
for key,value in data.items():
if key == u'deviceIP':
ipname =value
else: #json消息分类
if key == u'vehicles':
vehicle_list = value
vehicle_list.insert(0,ipname)
if key == u'laneRealTimeData':
lane_list = value
lane_list.insert(0,ipname)
if key == u'vehiclesFlow':
flow_list = value
flow_list.insert(0,ipname)
if key == u'vehicles' and len(vehicle_list) != 0:
vehicles_done(0)
if counter % 2 == 0
and len(lane_list) != 0: #时间控制
vehicles_done(1)
if counter % 60 == 0
and len(flow_list) != 0:
vehicles_done(2)
counter = counter + 1
#print(counter)
#print(buf[2:-2])
#print(data)
except:
print("ex")
soc.close()#关闭socket通讯
vehicle_file.close()
lane_file.close()
flow_file.close()
最后
以上就是开朗玉米为你收集整理的python接收TCP协议的Json格式消息,并保存.txt的全部内容,希望文章能够帮你解决python接收TCP协议的Json格式消息,并保存.txt所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复