Checkout Source Code
Run Matlab Server in one Terminal
$matlab -nodisplay
host='localhost';
port=5000;
s = server(host, port);
s.receive();
s.send('This is MatLab');
s.send('This is MatLab');
This is NodeJS
This is NodeJS
This is NodeJS
Run NodeJS client in another Terminal
$node
client = require('./client');
host='localhost';
port=5000;
c = new client(host, port);
c.receive();
This is MatLab
This is MatLab
c.send('This is NodeJS\n');
c.send('This is NodeJS\n');
c.send('This is NodeJS\n');
Enables sending messages from Matlab to NodeJS and vice versa just fine. Right what I was looking for.
ReplyDeleteNow, I am facing another problem, however, and I wonder if anyone can help me with this.
I am sending strings from Matlab to Node. Depending on the string, I want Node to perform specific commands. So I made the following modifications:
$node
> client = require('./client');
> host='localhost';
> port=5000;
> c = new client(host, port);
> var message = c.receive();
> if (message === "ping") {console.log("received ping");};
It seems to me as if no value is assigned to message. Is there any mistake in the code above or do i need to modify "receive" in client.js?
Thanks for some hints.
Add a callback function in the constructor of Client (in client.js) like this:
Delete// client.js
net = require('net');
function Client(host, port, callback){ // notice the addition callback
this.queue = [];
this.callbackfcn = callback; // we are now storing the callback function you provide when you construct
this.socket = new net.Socket();
this.socket.connect(port, host, function() {
console.log('Connected');
});
this.queue = [];
}
Client.prototype.send = function (data){
this.socket.write(data+'\n');
}
Client.prototype.receive = function (){
var that = this;
this.socket.on('data', function(data) {
that.queue.push(data);
// console.log(''+data);
that.callbackfcn(data); // your callback function will now be called whenever Client receives a message
});
}
Client.prototype.disconnect = function (){
this.socket.on('close', function() {
console.log('Connection closed');
this.socket.destroy();
});
}
module.exports = Client;
Now you can use the client.js file as follows:
$node
> client = require('./client');
> host='localhost';
> port=5000;
> var my_callback = function(message){ if (message === "ping") {console.log("received ping") });
> c = new client(host, port, my_callback });
Thank you very much. I am new to programming in JavaScript and didnt recognize c.receive as a callback function.
DeleteThis answer also helped a lot understanding asynchronus functions in JS
https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call
Hi, i want to know is there any way to add to matlab server deployable archive other files besides existing ones.
ReplyDelete