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

Web & réseau Delphi Discussion :

Connexion Deconnexion Socket communication balance


Sujet :

Web & réseau Delphi

  1. #1
    Membre régulier
    Profil pro
    Inscrit en
    Février 2010
    Messages
    533
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2010
    Messages : 533
    Points : 124
    Points
    124
    Par défaut Connexion Deconnexion Socket communication balance
    Bonjour à tous,

    J'ai créé un client socket me permettant de communiquer avec une balance i20 de Precia Molen (pour info http://www.developpez.net/forums/d15...cia-molen-i20/).

    Je lui envoi une demande de poids à ma balance et je cherche également à faire une demande de tare. Par contre, autant pour la demande de poids que pour la demande de tare ce n'est que lors de mon deuxième clic que j'ai une réponse .. Je me demande si je n'ai pas un problème de connexion déconnexion socket... besoin d'un peu d'aide ...
    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
    const
      iPort = 11001;
      sHost = '192.168.xx.xxx';
     
    //procedures fonctions
    function Connexion(csSock : TClientSocket; iPort : integer; sHost : string) : integer;
    function Deconnexion(csSock : TClientSocket) : integer;
     
    implementation
     
    {$R *.dfm}
    // ********* Fonction de connexion à la socket *************
    function Connexion(csSock : TClientSocket; iPort : integer; sHost : string) : integer;
    begin
      csSock.Port := iPort;
      csSock.Host := sHost;
      csSock.Open;
    end;
     
    // ******** Fonction de déconnexion à la socket ***********
    function Deconnexion(csSock : TClientSocket) : integer;
    begin
      csSock.Close;
    end;
     
    //---------------------------------------------------------------------------------------------------------------------
    procedure TForm1.ClientSocket1Connect(Sender: TObject;
      Socket: TCustomWinSocket);
    begin
      StatusBar1.SimpleText := 'Connecté à la balance i20';
    end;
     
    procedure TForm1.ClientSocket1Connecting(Sender: TObject;
      Socket: TCustomWinSocket);
    begin
      StatusBar1.SimpleText := 'Tentative de connexion à l''adresse : '+ Edit2.Text;
    end;
     
    procedure TForm1.ClientSocket1Disconnect(Sender: TObject;
      Socket: TCustomWinSocket);
    begin
      StatusBar1.SimpleText := 'Déconnecté';
    end;
     
    procedure TForm1.ClientSocket1Error(Sender: TObject;
      Socket: TCustomWinSocket; ErrorEvent: TErrorEvent;
      var ErrorCode: Integer);
    begin
      if ErrorEvent=eeConnect then
      begin
        ShowMessage('Impossible de se connecter à  '+Edit3.Text);
        ErrorCode:=0;// pour ne pas déclencher un autre message d'erreur par Delphi
      end;
      StatusBar1.SimpleText:='Déconnecté';
    end;
     
    procedure TForm1.ClientSocket1Read(Sender: TObject;
      Socket: TCustomWinSocket);
    var
      sMsg, sMsg2 : AnsiString;
      i : integer;
    const
      cstDebut=#2;
      cstFin=#13#10;
    begin
      sMsg := Socket.ReceiveText;
      Deconnexion(ClientSocket1);  // Une fois le message reçu plus besoin de la connexion socket, on ferme la connexion
      sMsg2 := Trim(Copy(sMsg,Pos(cstDEbut,sMsg)+Length(cstDebut)+2,Pos(cstFin,sMsg)-Pos(cstDebut,sMsg)+Length(cstDebut)));
      RichEdit1.Lines.Add(sMsg2);
      Edit1.Text := Copy(sMsg2,1,9);
     
    end;
     
     
     
    procedure TForm1.Button1Click(Sender: TObject);  // Bouton Demande de poids
    begin
      Connexion(ClientSocket1,iPort, sHost);
      ClientSocket1.Socket.SendText(#01#05#48#51#76#13#10);    // Demande de poids brut en décimal. SOH (Start of heading) + ENQ (Enquiry = Requête) + 03 (Poids net) + L (lecture seule) + CR + LF (Retour chariot)
    end;
     
    procedure TForm1.Button4Click(Sender: TObject);   // Bouton demande tarage
    begin
      Connexion(ClientSocket1,iPort, sHost);
      ClientSocket1.Socket.SendText(#01#16#48#52#77#13#10);  // Envoi demande de tarage = 0. SOH + DLE + 0 4 + M + CR + LF
      ClientSocket1.Socket.SendText(#01#05#48#51#76#13#10);  // Une fois le tarage effectué on affiche le poids pour vérification si poids = 0kg alors tarage effectué
    end;
    Nom : poidstare.png
Affichages : 347
Taille : 8,0 Ko
    Windows XP
    Delphi 7

    WinDev Mobile 17

  2. #2
    Membre émérite
    Avatar de ALWEBER
    Homme Profil pro
    Expert Delphi
    Inscrit en
    Mars 2006
    Messages
    1 496
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 69
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Expert Delphi

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 496
    Points : 2 762
    Points
    2 762
    Billets dans le blog
    10
    Par défaut
    Je n'ai pas vu d'erreurs particulières

    Ci dessous un petit programme pour que tu puisses comparer

    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
     
    unit FluxSocket1;
     
    interface
     
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, System.Win.ScktComp, ExtCtrls;
     
    type
      TMode = (Indefini, Client, Serveur);
     
      TForm1 = class(TForm)
        BtEnvoi: TButton;
        Memo1: TMemo;
        ServerSocket1: TServerSocket;
        ClientSocket1: TClientSocket;
        RadioGroup1: TRadioGroup;
        Button1: TButton;
        Edit1: TEdit;
        procedure BtEnvoiClick(Sender: TObject);
        procedure ServerSocket1ClientConnect(Sender: TObject;
          Socket: TCustomWinSocket);
        procedure ServerSocket1ClientRead(Sender: TObject;
          Socket: TCustomWinSocket);
        procedure RadioGroup1Click(Sender: TObject);
        procedure FormClose(Sender: TObject; var Action: TCloseAction);
        procedure ClientSocket1Disconnect(Sender: TObject;
          Socket: TCustomWinSocket);
        procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
          ErrorEvent: TErrorEvent; var ErrorCode: Integer);
        procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
        procedure FormActivate(Sender: TObject);
        procedure Button1Click(Sender: TObject);
      private
        stMessage: string;
        procedure ActiveSocket(mode1: TMode);
        procedure DesactiveSocket;
        { Déclarations privées }
      public
        { Déclarations publiques }
      end;
     
    var
      form1: TForm1;
      modeCS: TMode = Indefini;
     
    implementation
     
    {$R *.dfm}
     
    procedure TForm1.ActiveSocket(mode1: TMode);
    begin
      modeCS := mode1;
      case modeCS of
        Serveur:
          begin
            if not ServerSocket1.Active then
              ServerSocket1.Active := True;
            if ServerSocket1.Active then
              form1.caption := 'Serveur actif';
          end;
        Client:
          begin
            ClientSocket1.Active := True;
            if ClientSocket1.Active then
              form1.caption := 'Client Connecté';
          end;
      end;
    end;
     
    procedure TForm1.DesactiveSocket;
    begin
      case modeCS of
        Serveur:
          if ServerSocket1.Active then
            ServerSocket1.Active := False;
        Client:
          ClientSocket1.Active := False;
      end;
    end;
     
    procedure TForm1.FormActivate(Sender: TObject);
    begin
      Memo1.Lines.clear;
      {Randomize;
      form1.Left := round(Random(4)) * form1.Width;
      form1.Top := round(Random(3)) * form1.Height;
      }
    end;
     
    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
      DesactiveSocket;
    end;
     
    procedure TForm1.RadioGroup1Click(Sender: TObject);
    begin
      if RadioGroup1.ItemIndex = 0 then
          ActiveSocket(Serveur)
      else
          ActiveSocket(Client);
      RadioGroup1.enabled := False;
    end;
     
    procedure TForm1.BtEnvoiClick(Sender: TObject);
    var
      i1: Integer;
    begin
      case modeCS of
        Serveur:
          begin
            stMessage := 'Diffusion '+Edit1.text;
            for i1 := 0 to ServerSocket1.Socket.ActiveConnections - 1 do
              ServerSocket1.Socket.Connections[i1].SendText(stMessage);
          end;
        Client:
          begin
            stMessage := 'Client Envoi';
            if Edit1.text <> '' then
              stMessage := Edit1.text;
            ClientSocket1.Socket.SendText(stMessage)
          end;
      end;
     
    end;
     
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      case modeCS of
        Serveur:
        begin
          if ServerSocket1.Active then
            ServerSocket1.Active := False;
          if not ServerSocket1.Active then
            form1.caption := 'Serveur déconnecté';
        end;
        Client:
        begin
          ClientSocket1.Active := False;
          if not ClientSocket1.Active then
            form1.caption := 'Client non connecté';
        end;
      end;
    end;
     
    procedure TForm1.ClientSocket1Disconnect(Sender: TObject;
      Socket: TCustomWinSocket);
    begin
      Socket.SendText('Client Socket Disconnect');
    end;
     
    procedure TForm1.ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
      ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    begin
      ErrorCode := 0;
      ClientSocket1.Active := False;
      Memo1.text := Memo1.text + 'Pb connexion' + #13#10;
    end;
     
    procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
    begin
      Memo1.text := Memo1.text + 'serveur: ' + Socket.ReceiveText + #13#10;
    end;
     
    procedure TForm1.ServerSocket1ClientConnect(Sender: TObject;
      Socket: TCustomWinSocket);
    begin
      Socket.SendText('Connexion');
    end;
     
    procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
      Socket: TCustomWinSocket);
    begin
      Memo1.text := Memo1.text + 'Client ' + IntToStr(Socket.SocketHandle) + ' :' +
        Socket.ReceiveText + #13#10;
      Socket.SendText('Bien reçu ' + IntToStr(Socket.SocketHandle));
    end;
     
    end.

  3. #3
    Membre chevronné

    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Août 2002
    Messages
    1 288
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Août 2002
    Messages : 1 288
    Points : 1 936
    Points
    1 936
    Par défaut
    Pour moi, la déconnexion doit se faire dans la même procédure que celle qui appelle la connexion. Surtout pas quand on reçoit les données. Ex:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    Connexion(ClientSocket1,iPort, sHost);
    ClientSocket1.Socket.SendText(#01#16#48#52#77#13#10);  // Envoi demande de tarage = 0. SOH + DLE + 0 4 + M + CR + LF
     ClientSocket1.Socket.SendText(#01#05#48#51#76#13#10);
     Deconnexion(ClientSocket1);
    Delphi 7/XE2/XE3
    C#
    Oracle 9i à 12c
    SQL Server 2008 à 2014

  4. #4
    Membre régulier
    Profil pro
    Inscrit en
    Février 2010
    Messages
    533
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2010
    Messages : 533
    Points : 124
    Points
    124
    Par défaut
    Si je fais la déconnexion juste après ma demande, mon évènement OnRead sur lequel je récupère le message de la balance ne se déclenche pas.

    J'ai fait un autre test, si je fais un bouton connexion et un bouton déconnexion (et donc que j'enlève ma connexion avant ma demande [clique bouton demande poids] et ma déconnexion après réception du message [OnRead]) et que je fais clic bouton connexion, clic bouton poids, clic déconnexion je n'ai aucun soucis ça fonctionne ... pas besoin de cliquer deux fois sur la demande de poids ... (pareil pour la demande de la tare)

    Je ne comprend pas.

    Je me suis aperçue également que la différence entre le premier clic bouton demande poids (qui ne fonctionne pas) et le deuxième clic (qui fonctionne) sur le premier clic, l'évènement OnRead ne se déclenche pas et la déconnexion ne se fait donc pas ... j'ai beau retourner le problème dans tous les sens... je ne comprend pas ...
    Windows XP
    Delphi 7

    WinDev Mobile 17

  5. #5
    Membre émérite
    Avatar de ALWEBER
    Homme Profil pro
    Expert Delphi
    Inscrit en
    Mars 2006
    Messages
    1 496
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 69
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Expert Delphi

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 496
    Points : 2 762
    Points
    2 762
    Billets dans le blog
    10
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
            ClientSocket1.Active := True;
            if ClientSocket1.Active then
              form1.caption := 'Client Connecté';
    Tu peux lancer tes action de send dans un timer qui teste la propriété Active, ce qui laissera à ton programme le temps de se connecter ;

  6. #6
    Membre régulier
    Profil pro
    Inscrit en
    Février 2010
    Messages
    533
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2010
    Messages : 533
    Points : 124
    Points
    124
    Par défaut
    Comment ça lancer mes actions de Send dans un Timer ? (Je n'ai jamais utilisé ce composant)
    Windows XP
    Delphi 7

    WinDev Mobile 17

  7. #7
    Membre émérite
    Avatar de ALWEBER
    Homme Profil pro
    Expert Delphi
    Inscrit en
    Mars 2006
    Messages
    1 496
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 69
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Expert Delphi

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 496
    Points : 2 762
    Points
    2 762
    Billets dans le blog
    10
    Par défaut Un petit exemple
    Citation Envoyé par juju1988 Voir le message
    Comment ça lancer mes actions de Send dans un Timer ? (Je n'ai jamais utilisé ce composant)
    Ci dessous un exemple. Tu lances deux fois le programme l'un en serveur, l'autre en client

    Ex_socket.zip

    une variante sur la procedure TForm1.Timer1Timer

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    procedure TForm1.Timer1Timer(Sender: TObject);
    begin
      if ClientSocket1.Active then
      begin
        ClientSocket1.Socket.SendText(stMessage) ;
        Timer1.Enabled := false ;
      end;
    end;

  8. #8
    Expert éminent sénior
    Avatar de Paul TOTH
    Homme Profil pro
    Freelance
    Inscrit en
    Novembre 2002
    Messages
    8 964
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2002
    Messages : 8 964
    Points : 28 445
    Points
    28 445
    Par défaut
    la bonne séquence c'est

    Button1Click -> Button1.Enabled := False; Connect()
    OnConnect -> SendText()
    OnRead ->ReceiveText(); Disconnect()
    OnDisconnect -> Button1.Enabled := True;

    si tu appelles SendText() trop top, la connexion n'est pas encore établie. Lors de ton second clic, le Connect ne fait rien car tu es déjà connecté.
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  9. #9
    Membre régulier
    Profil pro
    Inscrit en
    Février 2010
    Messages
    533
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2010
    Messages : 533
    Points : 124
    Points
    124
    Par défaut
    Olala je suis désolée je n'avais pas vu vos réponses.
    Je regarde ça et je vous dis.

    EDIT :

    Nickel Paul j'ai suivi ton conseil ça fonctionne parfaitement merci.
    Windows XP
    Delphi 7

    WinDev Mobile 17

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

Discussions similaires

  1. Socket : Connexion/Deconnexion avec CAsyncSocket
    Par viklaus83 dans le forum MFC
    Réponses: 2
    Dernier message: 20/07/2009, 12h08
  2. Connexion via Socket JAVA
    Par jihene dans le forum API standards et tierces
    Réponses: 2
    Dernier message: 08/06/2006, 18h50
  3. [socket] Communication bloquante
    Par Tex-Twil dans le forum Développement
    Réponses: 3
    Dernier message: 29/03/2006, 16h33
  4. [Socket] Communication à l'aide de sockets (théorie)
    Par nicolas.pied dans le forum C++
    Réponses: 1
    Dernier message: 29/11/2005, 17h33
  5. [FLASH COM] Connexion de composants communication
    Par zaoueche dans le forum Flash
    Réponses: 3
    Dernier message: 31/01/2005, 12h57

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