使用Edge.js,在JavaScript中調用C# .Net

Edge.js可以讓開發者在JavaScript中調用C#的接口,提升應用的擴展能力。這裏介紹如何調用C#接口獲取圖片數據,並經過Node.js搭建的WebSocket server發送到Web客戶端。javascript

參考:How to Use Edge.js to Empower WebSocket Solutions in JavaScripthtml

經過.Net接口獲取圖片返回給JavaScript

先看下單純使用JavaScript來load本地圖片能夠這樣:
java

var fs = require('fs');
fs.readFile('Capture.jpg', function(err, data) {
  console.log(data.length); // image data
});
 

要使用Edge.js,使用下面的命令來安裝:node

npm install edge

建立C#文件nativeImageLoader.cs
git

#r "System.Drawing.dll"
using System.Threading.Tasks;
using System.Drawing;
 
public class Startup
{
    public async Task<object> Invoke(object input)
    {   
        byte[] imageBuffer;
        Image image = Image.FromFile("Capture.jpg");
        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
        {
            image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            imageBuffer = stream.GetBuffer();
        }
 
        return imageBuffer;
    }
}
 

在默認狀況下,edge加載的系統dll只有mscorlib.dll and System.dll,所以須要經過#r 「System.Drawing.dll」手動添加。github

如今在JavaScript層就能夠獲取圖像了:web

var nativeImageLoader = edge.func(require('path').join(__dirname, 'nativeImageLoader.cs'));
nativeImageLoader('load', function(error, result) {
            if (error) throw error;
            // result is the loaded image
 });
 

使用Node.js建立WebSocket解決方案

首先安裝WebSocket包:npm

npm install ws

幾行代碼搞定server的圖像數據發送:
c#

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({
        port: 8080
});
wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('Received: %s', message);
        nativeImageLoader('load', function(error, result) {
            if (error) throw error;
            ws.send(result); // send the captured image
        });
    });
});
 

運行server:websocket

node server.js

在客戶端中接收數據:

var ws = new WebSocket("ws://127.0.0.1:8080/");     
ws.binaryType = "arraybuffer";
 
ws.onopen = function() {    
   alert("Opened");    
   ws.send("I'm Dynamsoft");    
};    
 
ws.onmessage = function (evt) {     
    var bytes = new Uint8Array(evt.data);
    var data = "";
    var len = bytes.byteLength;
    for (var i = 0; i < len; ++i) {
        data += String.fromCharCode(bytes[i]);
    }
    var img = document.getElementById("image");
    img.src = "data:image/png;base64,"+window.btoa(data);   
};    
 
ws.onclose = function() {    
   alert("Closed");    
};    
 
ws.onerror = function(err) {    
   alert("Error: " + err);    
};
 

打開client.htm能夠看到收到的數據:

源碼

https://github.com/DynamsoftRD/WebSocket-in-JavaScript

git clone https://github.com/DynamsoftRD/WebSocket-in-JavaScript.git
相關文章
相關標籤/搜索