使用Edge.js,在JavaScript中调用C# .Net
jopen
10年前
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