DukeScript with Node.js backend
In one of our latest projects the customer has decided to use Node.js as a backend. So we decided to share a minimal demo how simple it is using DukeScript APIs.
You’ll need node installed and in addition the websocket module. Here’s the server, we’re using a websocket to make it a little fancier.
var ipaddress = 'localhost';
var port = 8085;
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server
, wss = new WebSocketServer({host:ipaddress, port:port});
wss.broadcast = function(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
console.log('send response');
client.send(data);
}
});
};
wss.on('connection', function (ws) {
ws.on('message', function (message) {
console.log('received message ' + message);
wss.broadcast("{message: 'message from server'}");
setInterval(function () {
wss.broadcast("{message: 'message "+i+" from server'}");
i++;
}, 5000);
});
});
The websocket server sends a simple JSON message every 5 seconds after we connected. Don’t worry too much about the server code. This is just for demo purposes. Now we need a Java model to read the message:
@Model(className = "Data", targetId = "", instance = true, properties = {
@Property(name = "message", type = String.class)
})
final class DataModel {
}
DukeScript has the extremely convenient @OnReceive annotation, that takes care of serializing messages to and deserializing messages from the server. So we extend our class with:
@OnReceive(url = "ws://localhost:8085", data = Data.class, method = "WebSocket")
public static void receive(Data data, Data message) {
if (message != null) {
ui.setMessage(message.getMessage());
} else { // null means: connection established
System.out.println("conection established");
}
}
This will generate a method in our Model class with all the boilerplate code. To establish the connection you once call the method with a null argument.
private static Data ui;
static void onPageLoad() throws Exception {
ui = new Data("Hallo");
ui.applyBindings();
ui.receive(null); //connect
}
After that you can call the receive method with data to send and receive messages via the websocket. The websocket can also push back messages to you. Let’s add a @Function, so we can send a message from the UI:
@Function
public static void send(Data data) {
data.receive(data);
}
Now we only need a UI to start the connection, so we add this to our View:
<input type="text" data-bind="textInput: message">
<button data-bind="click: send">Send Message</button>
The full code to play with is available on Github.
And if you want to code the Node based server in Java as well, have a look at this project: Node4J.
That’s it. Easy, isn’t it? Have fun coding DukeScript!