# coding=utf-8
#
#

import json
from mybase import *
from myconst import *

import os, socket


def Sende_MD_Befehl(Befehl, Anweisung, IPListe,Thread_Nr):
    debugmessage('Client-Thread (' + str(Thread_Nr) + ') - start: ' + Befehl + ' - ' + ','.join(IPListe))
    Verbindungsanz = 0
    SendeMessage_client = getMDJson(Befehl, Anweisung)
    for ClientIP in IPListe:
        debugmessage ('>>> Verbindugsaufbau zu '+ ClientIP)
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        client_socket.settimeout(SocketTimeout_CL / 1000.0 )
        try:
            client_socket.connect((ClientIP, MDPort))
            try:
                client_socket.sendall(SendeMessage_client)
                debugmessage('>>>   gesendet ' + SendeMessage_client.decode())
                Verbindungsanz += 1
            except Exception as e:
                debugmessage('>>>   sendall-fail: ' + str(e))
        except Exception as e:
            debugmessage('>>>   connect-fail: '+str(e))
        finally:
            client_socket.close()
    debugmessage('Client-Thread (' + str(Thread_Nr) + ') - beendet nach ' + str(Verbindungsanz) + ' Verbindungen.')


