IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau/Web Python Discussion :

Socket while ne revient pas dans ma boucle


Sujet :

Réseau/Web Python

  1. #1
    Membre régulier
    Inscrit en
    Novembre 2013
    Messages
    229
    Détails du profil
    Informations forums :
    Inscription : Novembre 2013
    Messages : 229
    Points : 109
    Points
    109
    Par défaut Socket while ne revient pas dans ma boucle
    Bonjour

    je met en place une com par socket
    J'ai un fichier client.py qui envoie les data vers le server avec une boucle while + input pour donner la commande mais ma boucle envoie une fois la command et ne reviens pas sur l'input
    La parti server répond bien a mes commandes.
    Je pense que c'est la partie socket qui bloque mais je ne vois pas quoi ?

    Nom : pbsocket.png
Affichages : 104
Taille : 6,8 Ko

    server.py
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    import socket
    import configparser
    from psu import Get_Tension_V1,Get_Tension_V2, Set_Tension_V1, Set_Tension_V2
    from psu import Get_Intensite_V1, Get_Intensite_V2, Set_Intensite_V1, Set_Intensite_V2
    from psu import V1_ON, V1_OFF, V2_ON, V2_OFF
    import logging
    import time
    import threading
     
    class plugin():
        def __init__(self) -> None:
            self.IP,self.PORT = "",""
            self.rep = ""
            self.s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
            self.parametrage()
            self.loggerinit()
            self.SocketConnect()
     
     
        def startlistening(self):
            self.t = threading.Thread(target=self.Listening)
            self.t.start()
     
        def date_time_log(self,sep="/"):
            now = time.localtime(time.time())
            annee = str(now.tm_year)
            mois = str(now.tm_mon)
            jour = str(now.tm_mday)
            heure = str(now.tm_hour)
            minute = str(now.tm_min)
            seconde = str(now.tm_sec)
            return jour.zfill(2) +sep + mois.zfill(2)+ sep + annee.zfill(4) + " " + heure.zfill(2) + ":" + minute.zfill(2) + ":" + seconde.zfill(2)
     
        def date_time(self):
            now = time.localtime(time.time())
            annee = str(now.tm_year)
            mois = str(now.tm_mon)
            jour = str(now.tm_mday)
            heure = str(now.tm_hour)
            minute = str(now.tm_min)
            seconde = str(now.tm_sec)
            return jour.zfill(2) +"_" + mois.zfill(2)+ "_" + annee.zfill(4)
     
        def parametrage(self):
            try:
                #param
                FileIni = "server.ini"
                config = configparser.ConfigParser()
                config.read(FileIni)
                self.IP = config["PARAMETRE"]["IP"]
                self.PORT = config["PARAMETRE"]["PORT"] 
            except Exception as exc:
                logging.critical(f"{self.date_time_log()} ==> {exc}")
     
        def loggerinit(self):
            logging.basicConfig(filename='Log_Server'  + str(self.date_time()) + ".txt",  level=logging.DEBUG)
     
        def SocketConnect(self):
            try:
                # Bind and listen
                self.s.bind((self.IP,int(self.PORT)))
                self.s.listen()
                print(f"Server Listening IP {self.IP} PORT {self.PORT}")
     
            except Exception as exc:
                logging.critical(f"{self.date_time_log()} ==> {exc}")
     
     
        def Listening(self):
            logging.info(str(self.date_time_log())  + f" : Server Listening IP {self.IP} PORT {self.PORT}")
            # Accept connections
            while(True):
                try:
                    (clientConnected, clientAddress) = self.s.accept()
                    print("Accepted a connection request from %s:%s"%(clientAddress[0], clientAddress[1]))
     
                    dataFromClient = clientConnected.recv(1024).decode("utf-8")
                    dataFromClient = dataFromClient.replace("\r","").replace("\n","")
                    print(dataFromClient)
     
                    app = str(dataFromClient).split(";")[0]
                    cmd = str(dataFromClient).split(";")[1]
                    logging.info(str(self.date_time_log())  + ' : Receive From BTMA : ' + str(dataFromClient))
                    exec("self.rep = " + cmd)
                    logging.info(str(self.date_time_log())  + ' : Receive From Plugin : ' + str(self.rep))
                    clientConnected.send(self.rep.encode())
     
                except Exception as exc:
                    logging.critical(f"{self.date_time_log()} ==> {exc}")
     
    if __name__ == "__main__":
        plug = plugin()
        plug.startlistening()
    client.py

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    import socket
    import time
    import configparser
    import logging
    import time
     
    #param
    FileIni = "server.ini"
    config = configparser.ConfigParser()
    config.read(FileIni)
    HOST = config["PARAMETRE"]["IPCPX"]
    PORT = config["PARAMETRE"]["PORTCPX"] 
     
     
    def date_time_log(sep="/"):
        now = time.localtime(time.time())
        annee = str(now.tm_year)
        mois = str(now.tm_mon)
        jour = str(now.tm_mday)
        heure = str(now.tm_hour)
        minute = str(now.tm_min)
        seconde = str(now.tm_sec)
        return jour.zfill(2) +sep + mois.zfill(2)+ sep + annee.zfill(4) + " " + heure.zfill(2) + ":" + minute.zfill(2) + ":" + seconde.zfill(2)
     
    def date_time():
        now = time.localtime(time.time())
        annee = str(now.tm_year)
        mois = str(now.tm_mon)
        jour = str(now.tm_mday)
        heure = str(now.tm_hour)
        minute = str(now.tm_min)
        seconde = str(now.tm_sec)
        return jour.zfill(2) +"_" + mois.zfill(2)+ "_" + annee.zfill(4)
     
    logging.basicConfig(filename='Log_Server'  + str(date_time()) + ".txt",  level=logging.DEBUG)
     
    # TENSION
     
    def Get_Tension_V1():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            s.send(b"V1?")
            retour = s.recv(1024).decode("utf-8")
            val = retour.replace("\r","").replace("\n","").split(" ")
            if len(val) > 1:
     
                return f"OK;{val[1]}"
     
            return "FAIL"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
     
    def Set_Tension_V1(val):
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "V1 {}".format(val)
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return("OK")
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def V1_ON():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "OP1 1"
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return "OK"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def V1_OFF():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "OP1 0"
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return "OK"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def Get_Tension_V2():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            s.send(b"V2?")
            retour = s.recv(1024).decode("utf-8")
            val = retour.replace("\r","").replace("\n","").split(" ")
            if len(val) > 1:
                return f"OK;{val[1]}"
            else:
                return "FAIL"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def Set_Tension_V2(val):
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "V2 {}".format(val)
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return "OK"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def V2_ON():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "OP2 1"
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return "OK"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def V2_OFF():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "OP2 0"
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return "OK"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    # INTENSITE
     
    def Get_Intensite_V1():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            s.send(b"I1?")
            retour = s.recv(1024).decode("utf-8")
            val = retour.replace("\r","").replace("\n","").split(" ")
            if len(val) > 1:
     
                return f"OK;{val[1]}"
     
            return "FAIL"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def Set_Intensite_V1(val):
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "I1 {}".format(val)
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return("OK")
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def Get_Intensite_V2():
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            s.send(b"I2?")
            retour = s.recv(1024).decode("utf-8")
            val = retour.replace("\r","").replace("\n","").split(" ")
            if len(val) > 1:
                return f"OK;{val[1]}"
            else:
                return "FAIL"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")
     
    def Set_Intensite_V2(val):
        s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        s.connect((HOST, int(PORT)))
        try:
            cmd = "I2 {}".format(val)
            b = bytes(cmd, 'utf-8') 
            s.send(b)
            return "OK"
        except Exception as exc:
            logging.critical(f"{date_time_log()} ==> {exc}")

  2. #2
    Expert éminent sénior
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 351
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 351
    Points : 36 875
    Points
    36 875
    Par défaut
    Citation Envoyé par gyver76370 Voir le message
    Je pense que c'est la partie socket qui bloque mais je ne vois pas quoi ?
    Il manque du code dans le client pour comprendre ce qu'il fait. Ceci dit, prenez le temps de faire un petit prototype, exemple de ce que vous voulez faire: un client qui envoie une commande à un serveur et attend sa réponse, c'est beaucoup moins de lignes de codes que celles que vous avez posté!
    Et si vous ne faites pas cet effort, vous ne vous êtes pas focalisé sur la compréhension du problème à résoudre mais à faire fonctionner au plus vite votre application...

    - W

  3. #3
    Membre régulier
    Inscrit en
    Novembre 2013
    Messages
    229
    Détails du profil
    Informations forums :
    Inscription : Novembre 2013
    Messages : 229
    Points : 109
    Points
    109
    Par défaut
    mauvais copier coller
    le code """" client "" est le code de l'appareil que je pilote

    j'ai mis le code du psu (appareil électronique piloter)

    je remet le bon code lundi

    désolé du dérangement

  4. #4
    Membre régulier
    Inscrit en
    Novembre 2013
    Messages
    229
    Détails du profil
    Informations forums :
    Inscription : Novembre 2013
    Messages : 229
    Points : 109
    Points
    109
    Par défaut
    bon j'ai regardé

    et ca marche plus qu'a comparer avec le code que j'ai au boulot
    je n'ai pas tout le code chez moi

    bon weekend

    server.py
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    import socket
    import configparser
    import logging
    import time
    import threading
     
    class plugin():
        def __init__(self) -> None:
            self.IP,self.PORT = "",""
            self.rep = ""
            self.s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
            self.parametrage()
            self.loggerinit()
            self.SocketConnect()
     
     
        def startlistening(self):
            self.t = threading.Thread(target=self.Listening)
            self.t.start()
     
        def date_time_log(self,sep="/"):
            now = time.localtime(time.time())
            annee = str(now.tm_year)
            mois = str(now.tm_mon)
            jour = str(now.tm_mday)
            heure = str(now.tm_hour)
            minute = str(now.tm_min)
            seconde = str(now.tm_sec)
            return jour.zfill(2) +sep + mois.zfill(2)+ sep + annee.zfill(4) + " " + heure.zfill(2) + ":" + minute.zfill(2) + ":" + seconde.zfill(2)
     
        def date_time(self):
            now = time.localtime(time.time())
            annee = str(now.tm_year)
            mois = str(now.tm_mon)
            jour = str(now.tm_mday)
            heure = str(now.tm_hour)
            minute = str(now.tm_min)
            seconde = str(now.tm_sec)
            return jour.zfill(2) +"_" + mois.zfill(2)+ "_" + annee.zfill(4)
     
        def parametrage(self):
            try:
                #param
                FileIni = "server.ini"
                config = configparser.ConfigParser()
                config.read(FileIni)
                self.IP = "127.0.0.1"
                self.PORT = "2201"
            except Exception as exc:
                logging.critical(f"{self.date_time_log()} ==> {exc}")
     
        def loggerinit(self):
            logging.basicConfig(filename='Log_Server'  + str(self.date_time()) + ".txt",  level=logging.DEBUG)
     
        def SocketConnect(self):
            try:
                # Bind and listen
                self.s.bind((self.IP,int(self.PORT)))
                self.s.listen()
                print(f"Server Listening IP {self.IP} PORT {self.PORT}")
     
            except Exception as exc:
                logging.critical(f"{self.date_time_log()} ==> {exc}")
     
     
        def Listening(self):
            logging.info(str(self.date_time_log())  + f" : Server Listening IP {self.IP} PORT {self.PORT}")
            # Accept connections
            while(True):
                try:
                    (clientConnected, clientAddress) = self.s.accept()
                    print("Accepted a connection request from %s:%s"%(clientAddress[0], clientAddress[1]))
     
                    dataFromClient = clientConnected.recv(1024).decode("utf-8")
                    dataFromClient = dataFromClient.replace("\r","").replace("\n","")
                    logging.info(str(self.date_time_log())  + ' : Receive From Client : ' + str(dataFromClient))
                    clientConnected.send("OK".encode())
     
                except Exception as exc:
                    logging.critical(f"{self.date_time_log()} ==> {exc}")
     
    if __name__ == "__main__":
        plug = plugin()
        plug.startlistening()


    client.py
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    #!/usr/bin/env python3
     
    import socket
    import time
    import logging
     
    HOST = '127.0.0.1'  # The server's hostname or IP address
    PORT = 2201       # The port used by the server
     
    def date_time_log(sep="/"):
        now = time.localtime(time.time())
        annee = str(now.tm_year)
        mois = str(now.tm_mon)
        jour = str(now.tm_mday)
        heure = str(now.tm_hour)
        minute = str(now.tm_min)
        seconde = str(now.tm_sec)
        return jour.zfill(2) +sep + mois.zfill(2)+ sep + annee.zfill(4) + " " + heure.zfill(2) + ":" + minute.zfill(2) + ":" + seconde.zfill(2)
     
    def date_time():
        now = time.localtime(time.time())
        annee = str(now.tm_year)
        mois = str(now.tm_mon)
        jour = str(now.tm_mday)
        heure = str(now.tm_hour)
        minute = str(now.tm_min)
        seconde = str(now.tm_sec)
        return jour.zfill(2) +"_" + mois.zfill(2)+ "_" + annee.zfill(4)
     
    logging.basicConfig(filename='Log_Server'  + str(date_time()) + ".txt",  level=logging.DEBUG)
     
     
    x =""
    while x.upper() != "EXIT":
        x=input("cmd ??")
        print(x)
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect((HOST, PORT))
            logging.info(str(date_time_log())  + ' : Send From Client : ' + str('toto'))
            s.sendall(bytes(x.encode()))
            data = s.recv(1024)
            logging.info(str(date_time_log())  + ' : Receive From server : ' + str(data))
            s.close()

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Utiliser un pas dans une boucle For .. to .. do
    Par colorid dans le forum Langage
    Réponses: 4
    Dernier message: 14/06/2009, 11h09
  2. boucle while - passe deux fois dans la boucle.
    Par Benji01 dans le forum VBA Access
    Réponses: 2
    Dernier message: 05/05/2008, 12h23
  3. Ne rentre pas dans la boucle
    Par choko62 dans le forum VB 6 et antérieur
    Réponses: 7
    Dernier message: 19/06/2007, 14h54
  4. le prog ne rentre pas dans la boucle
    Par Invité dans le forum Langage
    Réponses: 2
    Dernier message: 06/10/2006, 06h45
  5. ça rentre pas dans la boucle pendant l'exécution
    Par djouahra.karim1 dans le forum Bases de données
    Réponses: 9
    Dernier message: 15/01/2005, 15h41

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo