WebSocket callback to answer to message

10,480

Why don't you just send images as json-encoded array and then handle it on server-side? I've not run this code, but it should work.

let images = [
    "image1.jpg",
    "image2.jpg",
];

ws.send(JSON.stringify(images), function(event)
{
    // Do something with images
});
Share:
10,480
Matteo Monti
Author by

Matteo Monti

Updated on June 04, 2022

Comments

  • Matteo Monti
    Matteo Monti almost 2 years

    I am playing with a simple exercise with WebSockets. I have a NodeJS script that listens on a WebSocket, receives a file name, opens the file, and sends the content of the file back to the client through the WebSocket.

    Here is the code:

    var websocket_server = require('ws').Server;
    var server = new websocket_server({port: 1234});
    
    var fs = require('fs');
    
    server.on('connection', function connection(socket)
    {
      socket.on('message', function request(file_name)
      {
        fs.readFile(file_name, function(error, data)
        {
          if(error)
            throw error;
    
          socket.send(data, {binary: true});
        });
      });
    });
    

    On the client side, I use a WebSocket to load an image and display it in the page:

    <!DOCTYPE html>
    <html>
    <head>
        <title>My Little Project</title>
        <script type = "text/javascript">
            var ws = new WebSocket("ws://127.0.0.1:1234");
            ws.binarytype = "blob";
            ws.onmessage = function(event)
            {
                var img = document.createElement("img");
                img.src = (window.URL || window.webkitURL).createObjectURL(event.data);
                document.body.appendChild(img);
            }
    
            ws.onopen = function(event)
            {
                ws.send("image1.jpg")
            }
        </script>
    </head>
    <body>
    </body>
    </html>
    

    Now, this example works fine, and I am happy. What makes me sad is that I would now like to ask the server for multiple images, and to do something with each.

    I know that I could serialize all my requests by doing something like:

    ws.onmessage = function(event)
    {
        // Do something with image1.jpg
        ws.onmessage = function(event)
        {
            // Do something with image2.jpg
            // And so on
        }
        ws.send("image2.jpg");
    };
    ws.send("image1.jpg");
    

    But this is serial, which adds overhead and so on. What I would like to get is something like:

    ws.send("image1.jpg", function(event)
    {
        // Do something with image1.jpg
    });
    
    ws.send("image2.jpg", function(event)
    {
        // Do something with image2.jpg
    });
    
    // And so on
    

    I have no clue on how to do this neither on the client nor on the server, so any help would be greatly appreciated.