Outils pour utilisateurs

Outils du site


serveur_websocket

Ceci est une ancienne révision du document !


Serveur Websocket

Un tutoriel permettant de débuter avec la librairie LibWebSocket a été rédigé en anglais à cette page.

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.

Matériel :

  • Raspberry 3 modèle B+
  • Carte SD 16 Go

Installation de LibWebSockets

Configuration

Installer la version Raspbian Stretch Lite 2019-04-08

En configuration supplémentaire, changer le nom en serveurwebsocket

sudo raspi-config

Aller dans - 2 Network Options - puis - N1 Hostname - puis changer le nom en : serveurwebsocket

Valider, puis aller dans - 4 Localisation Options - puis dans - I2 Change Timezone - et choisisse votre région puis la ville de référence et valider

Aller sur Finish puis yes pour redémarrer.

Installation des librairies complémentaires

sudo apt-get install cmake
sudo apt-get install git-core
sudo apt-get install libssl-dev

LibWebsockets

git clone https://github.com/warmcat/libwebsockets
cd libwebsockets
mkdir build
cd build
cmake .. -DLWS_IPV6=OFF -DLWS_MAX_SMP=8
make
sudo make install
cd

Pour verifier que tout fonctionne bien

libwebsockets-test-server

Taper dans votre navigateur préféré :

http://127.0.0.1:7681/

Si le compteur démarre, alors la librairie est bien installée.

Voici le code mis à jour :

// gcc -Wall testServeur.c -o testServeur -lwebsockets
 
 
#include <stdio.h>
#include <stdlib.h>
#include <libwebsockets.h>
 
static int
lws_callback_http(
 
                  struct lws *wsi,
                  enum lws_callback_reasons reason,
                  void *user,
                  void *in,
                  size_t len
                  ) {
    switch (reason) {
        case LWS_CALLBACK_ESTABLISHED:
            printf("connection established\n");
            break;
        case LWS_CALLBACK_RECEIVE: {
            unsigned char *buf = (unsigned char*)
            malloc(LWS_SEND_BUFFER_PRE_PADDING + len
                   + LWS_SEND_BUFFER_POST_PADDING);
            int i;
            for (i=0; i < len; i++) {
                buf[LWS_SEND_BUFFER_PRE_PADDING + (len - 1) - i ] =
                ((char *) in)[i];
            }
 
            printf("received data: %s, replying: %.*s\n", (char *) in,
                   (int) len, buf + LWS_SEND_BUFFER_PRE_PADDING);
 
            lws_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING],
                      len, LWS_WRITE_TEXT);
            free(buf);
            break;
        }
        default:
            break;
    }
 
    return 0;
}
 
static struct lws_protocols protocols[] = {
    {
        "http-only",   // name
        lws_callback_http, // callback
        0              // per_session_data_size
    },
    {
        NULL, NULL, 0   /* End of list */
    }
};
 
static const struct lws_extension exts[] = {
    {
        "permessage-deflate",
        lws_extension_callback_pm_deflate,
        "permessage-deflate"
    },
    { NULL, NULL, NULL /* terminator */ }
};
 
int main(void) {
    int port = 9000;
    const char *interface = NULL;
    struct lws_context *context;
    int opts = 0;
 
    // create libwebsocket context representing this server
    struct lws_context_creation_info info;
 
    memset(&info, 0, sizeof info);
    info.port = port;
    info.iface = interface;
    info.protocols = protocols;
    info.extensions = exts;
    //if (!use_ssl) {
    info.ssl_cert_filepath = NULL;
    info.ssl_private_key_filepath = NULL;
    //} else {
    //  info.ssl_cert_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.pem";
    //  info.ssl_private_key_filepath = LOCAL_RESOURCE_PATH"/libwebsockets-test-server.key.pem";
    //}
    info.gid = -1;
    info.uid = -1;
    info.options = opts;
 
    context = lws_create_context(&info);
 
    if (context == NULL) {
        fprintf(stderr, "libwebsocket init failed\n");
        return -1;
    }
 
    printf("starting server...\n");
    while (1) {
        lws_service(context, 50);
    }
 
    lws_context_destroy(context);
 
    return 0;
}

Compilation :

gcc -Wall testServeur.c -o testServeur -lwebsockets

Execution :

./testServeur

Créer le fichier index.html avec le contenu suivant :

<!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>

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 !

serveur_websocket.1584626043.txt.gz · Dernière modification : 2020/03/19 13:54 de Mushussu