title: C# websocket: how do I send binary data to a client?
body: <p>I am trying to send a image (<code>.png</code>) as a <code>binary blob</code> to a <code>javascript</code> client:</p>
  
  <pre><code>  static Byte[] imageResponse(string pngPath)
    {
          Byte[] image = System.IO.File.ReadAllBytes(pngPath);
          ulong n = (ulong) image.Length;
          byte[] data = new byte[n + 10];
          data[0] = 130; // binary ?
          data[1] = 127;
          Byte[] na = BitConverter.GetBytes(n); // correct endinaness?
          Array.Copy(na, 0, data, 2, 8);
          Array.Copy(image, 0, data, 10, (int) n);
          return data;
    }
  
   string path = "C:/tmp/crl3400.png";
   Byte[] bresponse = imageResponse(path);
   stream.Write(bresponse, 0, bresponse.Length);
  </code></pre>
  
  <p>However in the client I am not receiving any message:</p>
  
  <pre><code>var socket = new WebSocket( "ws://127.0.0.1:80" );
  socket.binaryType = "arraybuffer"; // allow both text and binary data to be transfered.
  socket.onopen = function ( event ) {
      alert( "WebSocket opened!" );
      socket.send( "Hello server!" );
  };
  socket.onmessage = function ( event ) {
      alert( "onmessage" );
      var arrayBufferView = new Uint16Array( event.data );
      var blob = new Blob( [arrayBufferView], { type: "image/png" } );
      var urlCreator = window.URL || window.webkitURL;
      var imageUrl = urlCreator.createObjectURL( blob );
      var img = document.querySelector( "#image" );
      img.src = imageUrl;
  };
  socket.onerror = function ( event ) {
      alert( "Error" );
  }
  </code></pre>
  
  <p>What could be wrong?
  Things worked when I sent the text <code>"Hello client!"</code>. I am not getting an <code>Error</code> alert. On the server I am receiving <code>"Hello server!"</code> fine. </p>