C#websocket:如何将二进制数据发送到客户端?

时间:2015-11-18 14:25:17

标签: c# .net websocket

我正在尝试将图像(.png)作为二进制blob发送到javascript客户端:

  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);

但是在客户端我没有收到任何消息:

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");
    }

可能有什么不对? 当我发送文本" Hello客户端时,情况有效!"。我没有收到错误提醒。在我收到的服务器上" Hello服务器!"精细。

1 个答案:

答案 0 :(得分:2)

enter image description here

msg.data是Blob的类型,所以你只需使用urlCreator.createObjectURL(blob);方法bla bla bla ....