import socket
from threading import Thread
import time
import json

ADDRESS =('192.168.50.188',8)
g_socket_server= None
g_conn_poll = {}

def init():
    global  g_socket_server
    g_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    g_socket_server.bind(ADDRESS)
    g_socket_server.listen(5)
    print('server start at: %s:%s' % ADDRESS)
    print('wait for connection...')

def accept_client():
    while True:
      client, info = g_socket_server.accept()
      thread = Thread(target=message_handle,args=(client,info))
      thread.setDaemon(True)
      thread.start()


def message_handle(client,info):
      global g_conn_poll
      client.sendall("connect server successfully!".encode(encoding='utf8'))
      while True:
        try:
          byte = client.recv(1024)
          msg=byte.decode(encoding='utf8')
          jd=json.loads(msg)
          cmd=jd['COMMAND']
          client_type=jd['client_type']
          if 'CONNECT'==cmd:
              g_conn_poll[client_type]=client
              print('on client connect:'+client_type,info)
          elif 'SEND_DATA'==cmd:
              print('recv client msg:'+client_type,jd['data'])
        except Exception as e:
            print(e)
            print("client offline  " + client_type)
            break

init()
while True:
  thread = Thread(target=accept_client)
  thread.setDaemon(True)
  thread.start()
