title: WebSocket callback to answer to message
body: <p>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.</p>
  
  <p>Here is the code:</p>
  
  <pre><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});
      });
    });
  });
  </code></pre>
  
  <p>On the client side, I use a WebSocket to load an image and display it in the page:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;title&gt;My Little Project&lt;/title&gt;
      &lt;script type = "text/javascript"&gt;
          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")
          }
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>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.</p>
  
  <p>I know that I could serialize all my requests by doing something like:</p>
  
  <pre><code>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");
  </code></pre>
  
  <p>But this is serial, which adds overhead and so on. What I would like to get is something like:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I have no clue on how to do this neither on the client nor on the server, so any help would be greatly appreciated.</p>