#!/usr/bin/python
#-*-coding:utf-8 -*-
import socket
import cv2
import numpy
import time
import queue
pictures=[]
q_pictures = queue.Queue(2)
# q_pictures.get()

# 接受图片大小的信息
def recv_size(sock, count):
    buf = b''
    while count:
        newbuf = sock.recv(count)
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)
    return buf

# 接收图片
def recv_all(sock, count):
    buf =b""
    while count > 0:
        if count >= 40960000:
            data = sock.recv(40960000)
        else:
            data = sock.recv(count)
        if not data:
            continue
        count -= len(data)
        buf += data

    # buf = sock.recv(count)
    print("received ",len(buf))
    return buf

# socket.AF_INET用于服务器与服务器之间的网络通信
# socket.SOCK_STREAM代表基于TCP的流式socket通信
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置地址与端口，如果是接收任意ip对本服务器的连接，地址栏可空，但端口必须设置
address = ('', 12900)
s.bind(address) # 将Socket（套接字）绑定到地址
s.listen(True) # 开始监听TCP传入连接
print ('Waiting for images...')
# 接受TCP链接并返回（conn, addr），其中conn是新的套接字对象，可以用来接收和发送数据，addr是链接客户端的地址。
conn, addr = s.accept()
print("addr==",addr)
while 1:
    start=time.time()
    length = recv_size(conn,16) #首先接收来自客户端发送的大小信息
    print("length=", length)
    length_str=''
    if  length is not None:
         length_str=bytes.decode(length)
    if isinstance (length_str,str): #若成功接收到大小信息，进一步再接收整张图片
        stringData = recv_all(conn, int(length))
        data = numpy.fromstring(stringData, dtype='uint8')
        decimg=cv2.imdecode(data,1) #解码处理，返回mat图片
        q_pictures.put(decimg)
        cv2.imshow('SERVER',decimg)
        end = time.time()

        #print('Image recieved successfully!')
    if cv2.waitKey(10) == 27:
        break
        #conn.send(b"Server has recieved messages!")
    if cv2.waitKey(10) == 27:
        break

    print("total time==",end-start)
s.close()
cv2.destroyAllWindows()


# #!/usr/bin/python
# #-*-coding:utf-8 -*-
# import socket
# import cv2
# import numpy
# import time
#
# # 接受图片大小的信息
# def recv_size(sock, count):
#     buf = b''
#     while count:
#         newbuf = sock.recv(count)
#         if not newbuf: return None
#         buf += newbuf
#         count -= len(newbuf)
#     return buf
# # 接收图片
# def recv_all(sock, count):
#     buf =b""
#     while count > 0:
#         if count >= 40960000:
#             data = sock.recv(40960000)
#         else:
#             data = sock.recv(count)
#         if not data:
#             continue
#         count -= len(data)
#         buf += data
#     # buf = sock.recv(count)
#     print("received ",len(buf))
#     return buf
#
# # socket.AF_INET用于服务器与服务器之间的网络通信
# # socket.SOCK_STREAM代表基于TCP的流式socket通信
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# # 设置地址与端口，如果是接收任意ip对本服务器的连接，地址栏可空，但端口必须设置
# address = ('', 12900)
# s.bind(address) # 将Socket（套接字）绑定到地址
# s.listen(True) # 开始监听TCP传入连接
# #s.setblocking(True)
# #s.settimeout(0.5)
# print ('Waiting for images...')
# # 接受TCP链接并返回（conn, addr），其中conn是新的套接字对象，可以用来接收和发送数据，addr是链接客户端的地址。
# conn, addr = s.accept()
#
# print("addr==",addr)
# while 1:
#     start=time.time()
#     length = recv_size(conn,16) #首先接收来自客户端发送的大小信息
#     print("length=", length)
#     length_str=''
#     if  length is not None:
#          length_str=bytes.decode(length)
#     if isinstance (length_str,str): #若成功接收到大小信息，进一步再接收整张图片
#         img_bytes = recv_all(conn, int(length))
#         data = numpy.fromstring(img_bytes, dtype='uint8')
#         image = numpy.array(data).reshape(600, 1000, 3)
#         # decimg=cv2.imdecode(data,1) #解码处理，返回mat图片
#         cv2.imshow('SERVER',image)
#         end = time.time()
#
#         print('Image recieved successfully!')
#     if cv2.waitKey(10) == 27:
#         break
#         #conn.send(b"Server has recieved messages!")
#     if cv2.waitKey(10) == 27:
#         break
#
#     print("total time==",end-start)
# s.close()
# cv2.destroyAllWindows()

