# -*- coding: utf-8 -*-

import socket
import cv2
import numpy as np
import time

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定端口:
s.bind(('127.0.0.1', 9999))

print('Bind UDP on 9999...')
i=0
depth_img=[]
is_begin=False
t=0
flag=0  # 表示接收起始命令
while True:
    if flag==0:
        data, addr = s.recvfrom(400000)
        h=np.fromstring(data, np.uint16)
        #print(h)
        print("h[0]:",h[0],"h[2]:",h[2])
        print(h[0]==22,h[2]==158)
        if (h[0]==22)&(h[2]==158):
            is_begin=True
            flag=1
            print('begin to receive frame...')


    if is_begin==True:
        t=time.time()

        data, addr = s.recvfrom(100000)
        data_decode = np.fromstring(data, np.uint16)
        # print(data_decode) # 打印接收到的数据
        depth_img.append(data_decode)
        i=i+1
        print(i)
    # print('Received from %s:%s.' % addr)
    if (i%720==0) & (i!=0):  # 假设不丢任何帧  则收到开始指令后的720则为一个frame
        i=0
        print('time:',time.time() - t)
        depth_img_array=np.array(depth_img)
        depth_img = []
        flag=0
        print('received one frame')
        print('receive——client:', depth_img_array[550, 900])

    # print(np.array(depth_img).shape)
    # cv2.imshow('result',img_decode)
    # cv2.waitKey(5)
    # reply = "get message!!!"
    # s.sendto(reply.encode('utf-8'), addr)
    # cv2.destroyAllWindows()




