Outils pour utilisateurs

Outils du site


serveur_websocket

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
serveur_websocket [2019/06/25 09:32] Mushussuserveur_websocket [2020/07/22 14:19] (Version actuelle) Mushussu
Ligne 2: Ligne 2:
 Un tutoriel permettant de débuter avec la librairie LibWebSocket a été rédigé en anglais à cette [[https://medium.com/@martin.sikora/libwebsockets-simple-websocket-server-68195343d64b|page]]. Un tutoriel permettant de débuter avec la librairie LibWebSocket a été rédigé en anglais à cette [[https://medium.com/@martin.sikora/libwebsockets-simple-websocket-server-68195343d64b|page]].
  
-Il paraissait répondre aux attentes des débutants, mais certaine partie du code sont erronées et la version de la librairie n'est plus compatible avec la version récente de LibWebSocket.+Il paraissait répondre aux attentes des débutants, mais certaines parties du code sont erronées et la version de la librairie n'est plus compatible avec la version récente de LibWebSocket.
  
 Voici donc une réactualisation du tutoriel. Voici donc une réactualisation du tutoriel.
  
 Matériel : Matériel :
-  * Liste à puceRaspberry 3 modèle B++  * Raspberry 3 modèle B+
   * Carte SD 16 Go   * Carte SD 16 Go
  
Ligne 26: Ligne 26:
   sudo apt-get install git-core   sudo apt-get install git-core
   sudo apt-get install libssl-dev   sudo apt-get install libssl-dev
 +  sudo apt-get install zlib1g-dev
      
 === LibWebsockets === === LibWebsockets ===
 +
 +Ce tutoriel fonctionne avec la version 3.2 de LibWebSocket, voici donc la procédure pour l'installer :
 +
   git clone https://github.com/warmcat/libwebsockets   git clone https://github.com/warmcat/libwebsockets
   cd libwebsockets   cd libwebsockets
 +  git checkout v3.2-stable
   mkdir build   mkdir build
   cd build   cd build
-  cmake .. -DLWS_IPV6=OFF+  cmake .. -DLWS_IPV6=OFF -DLWS_MAX_SMP=8 -DLWS_WITHOUT_EXTENSIONS=OFF
   make   make
   sudo make install   sudo make install
   cd   cd
 +  sudo ldconfig
 Pour verifier que tout fonctionne bien  Pour verifier que tout fonctionne bien 
   libwebsockets-test-server   libwebsockets-test-server
 Taper dans votre navigateur préféré : Taper dans votre navigateur préféré :
-  http://serveurwebsocket:7681/+  http://127.0.0.1:7681/
 Si le compteur démarre, alors la librairie est bien installée. Si le compteur démarre, alors la librairie est bien installée.
  
Ligne 45: Ligne 51:
  
 <code c> <code c>
-// gcc -Wall ServeurMinitelWeb.c -o ServeurMinitelWeb -Llibwebsockets/build/lib -lwebsockets +// gcc -Wall testServeur.c -o testServeur -lwebsockets 
-  + 
- +
 #include <stdio.h> #include <stdio.h>
 #include <stdlib.h> #include <stdlib.h>
 #include <libwebsockets.h> #include <libwebsockets.h>
- +
 static int static int
 lws_callback_http( lws_callback_http(
-  +                   
-                         struct lws *wsi, +                  struct lws *wsi, 
-                         enum lws_callback_reasons reason, +                  enum lws_callback_reasons reason, 
-                         void *user, +                  void *user, 
-                         void *in, +                  void *in, 
-                         size_t len +                  size_t len 
-                         ) {+                  ) {
     switch (reason) {     switch (reason) {
         case LWS_CALLBACK_ESTABLISHED:         case LWS_CALLBACK_ESTABLISHED:
Ligne 74: Ligne 80:
                 ((char *) in)[i];                 ((char *) in)[i];
             }             }
- +            
             printf("received data: %s, replying: %.*s\n", (char *) in,             printf("received data: %s, replying: %.*s\n", (char *) in,
                    (int) len, buf + LWS_SEND_BUFFER_PRE_PADDING);                    (int) len, buf + LWS_SEND_BUFFER_PRE_PADDING);
- +            
             lws_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],             lws_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
-                               len, LWS_WRITE_TEXT);+                      len, LWS_WRITE_TEXT);
             free(buf);             free(buf);
             break;             break;
Ligne 86: Ligne 92:
             break;             break;
     }     }
- +    
     return 0;     return 0;
 } }
- +
 static struct lws_protocols protocols[] = { static struct lws_protocols protocols[] = {
     {     {
Ligne 100: Ligne 106:
     }     }
 }; };
- +
 static const struct lws_extension exts[] = { static const struct lws_extension exts[] = {
     {     {
Ligne 109: Ligne 115:
     { NULL, NULL, NULL /* terminator */ }     { NULL, NULL, NULL /* terminator */ }
 }; };
- +
 int main(void) { int main(void) {
     int port = 9000;     int port = 9000;
Ligne 115: Ligne 121:
     struct lws_context *context;     struct lws_context *context;
     int opts = 0;     int opts = 0;
- +    
     // create libwebsocket context representing this server     // create libwebsocket context representing this server
     struct lws_context_creation_info info;     struct lws_context_creation_info info;
- +    
     memset(&info, 0, sizeof info);     memset(&info, 0, sizeof info);
     info.port = port;     info.port = port;
Ligne 134: Ligne 140:
     info.uid = -1;     info.uid = -1;
     info.options = opts;     info.options = opts;
- +    
     context = lws_create_context(&info);     context = lws_create_context(&info);
- +    
     if (context == NULL) {     if (context == NULL) {
         fprintf(stderr, "libwebsocket init failed\n");         fprintf(stderr, "libwebsocket init failed\n");
         return -1;         return -1;
     }     }
- +    
     printf("starting server...\n");     printf("starting server...\n");
     while (1) {     while (1) {
         lws_service(context, 50);         lws_service(context, 50);
     }     }
- +    
     lws_context_destroy(context);     lws_context_destroy(context);
- +    
     return 0;     return 0;
 } }
 +
 </code> </code>
  
 +Compilation :
 +  gcc -Wall testServeur.c -o testServeur -lwebsockets
 +Execution :
 +  ./testServeur
 +  
 +Créer le fichier index.html avec le contenu suivant :
 +<code html>
 +<!DOCTYPE html>
 +<html>
 +<head>
 +<meta charset="utf-8">
 +<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
 +</script>
 +<script type="text/javascript">
 +$(function() {
 +    window.WebSocket = window.WebSocket || window.MozWebSocket;
 +    var websocket = new WebSocket(
 +        'ws://127.0.0.1:9000', 'http-only');
 +    websocket.onopen = function () {
 +        $('h1').css('color', 'green');
 +    };
 +    websocket.onerror = function () {
 +        $('h1').css('color', 'red');
 +    };
 +    websocket.onmessage = function (message) {
 +        console.log(message.data);
 +        $('div').append($('<p>', { text: message.data }));
 +    };
 +    $('button').click(function(e) {
 +        e.preventDefault();
 +        websocket.send($('input').val());
 +        $('input').val('');
 +    });
 +});
 +</script>
 +</head>
 +<body>
 +<h1>WebSockets test</h1>
 +<form>
 +<input type="text" />
 +<button>Send</button>
 +</form>
 +<div></div>
 +</body>
 +</html>
 +</code>
 +
 +L'ouvrir dans votre navigateur préféré. 
 +
 +WebSockets test doit être inscrit en vert ce qui signifie que la connection WebSocket fonctionne bien.
 +
 +Amusez-vous !
 {{tag>raspberry_pi serveur sylvain}} {{tag>raspberry_pi serveur sylvain}}
serveur_websocket.1561455162.txt.gz · Dernière modification : 2019/06/25 09:32 de Mushussu