使用Edge.js,在JavaScript中調用C# .Net
Edge.js能夠讓開發者在JavaScript中調用C#的接口,提高應用的擴展能力。這里介紹如何調用C#接口獲取圖片數據,并通過Node.js搭建的WebSocket server發送到Web客戶端。
參考:How to Use Edge.js to Empower WebSocket Solutions in JavaScript
通過.Net接口獲取圖片返回給JavaScript
先看下單純使用JavaScript來load本地圖片可以這樣:
var fs = require('fs'); fs.readFile('Capture.jpg', function(err, data) { console.log(data.length); // image data });
要使用Edge.js,使用下面的命令來安裝:
npm install edge
創建C#文件nativeImageLoader.cs:
#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”手動添加。
現在在JavaScript層就可以獲取圖像了:
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 install ws
幾行代碼搞定server的圖像數據發送:
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:
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
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!