How to Use Edge.js to Empower WebSocket Solutions in JavaScript

A few days ago, I read the article – Run .NET and Node.js code in-process with Edge.js, which inspired me to try a new way of WebSocket solutions in JavaScript. It is known that Node.js makes applications, which written in JavaScript, run on server-side. Let’s see how we can quickly implement image transmission between servers and clients in a few lines of code.

Loading Image Files in JavaScript and .NET

Generally, we can load image files in JavaScript like this:

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

The Edge.js connects Node.js and .NET in process. We can script C# from a Node.js process. To install edge package:

npm install edge

Let’s create a C# file nativeImageLoader.cs, and write a piece of code:

#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;
    }
}

By default, edge only references mscorlib.dll and System.dll. The #r “System.Drawing.dll” is used for loading additional assemblies.

Now we can get the JavaScript proxy:

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

Create a WebSocket Server in JavaScript

To install WebSocket package:

npm install ws

Create and launch a WebSocket 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
        });
    });
});

Run the server:

node server.js

In client.js, set the binary type of WebSocket:

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

Open client.htm to receive the loaded image.

nodejs_websocket

Source Code

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