How to use socket.write inside a function - javascript

var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {
console.log('closed');
});
// connection.write('100');
connection.pipe(connection);
});
server.listen(5001, function() {
console.log('server is listening');
});
function addInput(){
var value = document.getElementById("textId").value;
console.log(value);
document.getElementById("textId").value="";
//connection.write(value);
}
I want to send data to the client in the button function addinput, but I can't send it, how can I use socket.write in the function

Is that code that you commented (connection.write(value);) supposed to work?
You won't be able to make it work since connection is only within the scope of the function you wrote into var server.
Other than that, to get your server to do anything you'll have to make a request to it, possibly with net.createConnection() (check doc here: https://nodejs.org/api/net.html). I'm not seeing any code in your example that would do that so far.

Related

NodeJS - where to place functions for eval()

I have a NodeJS-Server which communicated with the fronend via Websocket-Connection.
When the Server gets a on('message'), it should run a function which name is given the message via eval().
it workes fine, unless I completely don't know where to put the funcions to be called.
var http = require('http');
var ws = require('ws');
function render(vars) {
var server = http.createServer(function(req, res) {
.....
});
/* WEBSOCKET */
var wsServer = new ws.Server({server});
wsServer.on('connection', socket => {
socket.on('message', message => {
console.log('WS from template <-- ', message);
var wsIn = JSON.parse(message);
eval(wsIn.action);
});
});
}
when a message is incoming, eval(wsIn.action) should run a function called.. .lets assume runme.. so where would I now need to declare this function ? I try everything but whatever I do, i get
ReferenceError:: runme is not defined
edit:
I found out something interesting:
when i call a function normal like runme(); in my onMessage.. everything is cool.. but with eval(runme); nothing happens.. no error, no output, nothing..

How a function is getting called with correct request & response objects?

I have a piece of code:
var http = require('http');
function createApplication() {
let app = function(req,res,next) {
console.log("hello")
};
return app;
}
app = createApplication();
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Nothing fancy here. But when I run this code and go to localhost:3000, I can see hello is getting printed. I'm not sure how this function is getting called at all. Also, the function receives the req & res objects as well. Not sure whats happening here.
http.createServer() has a couple optional arguments. One being requestListener which is
https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener
The requestListener is a function which is automatically added to the
'request' event.
Since you call your listen() like so app.listen(), this inside that function is going to be a reference to the function you made and returned in createApplication. So you are basically doing:
http.createServer(function(req,res,next) {
console.log("hello")
});
Hence your function is added as a callback for any request, and thus why any request you make will create a console log of hello.
If you want an equivalent more straight forward example
var http = require('http');
var server = http.createServer();
server.on('request',function(req,res,next) {
//callback anytime a request is made
console.log("hello")
});
server.listen(3000);

nodejs and mqtt sending message either once or constantly

I am using NodeJS with the express and mqtt packages.
Whenever the user pushes the button with the value 'test' a MQTT message should be sent.
However, whenever I send the mqtt message it is send either once when I use 'client.end()' or it keeps on sending the message constantly. I canĀ“t send it twice when I push the button again
I use following code:
module.exports =
{
Send
};
function Send(User){
client.on('connect', function() {
client.publish('alarm/reset', 'Hallo' + Test);
client.end();
});
}
In the '\' following code is used
router.post('/', Authencitation, function(req,res){
var test = req.body.test;
if (test == 'test')
{
reset.Send(req.session.user);
console.log('inside reset');
}
res.redirect('/');
});
However, I alway get inside the function inside reset whenever the button is clicked. It seems it is a mistake made in the function Send(User) but I cannot spot the error.
Following solution worked for me:
function Send(Test){
var mqtt = require('mqtt');
var client = mqtt.connect()
client.on('connect', function() {
client.publish('Test', 'Hallo' + username);
client.end();
});
}

Node.js module level variables are undefined

I'm having an issue accessing the scope of a module level variable from within a function inside of said module. See below...
var socketio = require('socket.io');
var socket = socketio.listen();
var myCustomModule = require('./lib/mycustommodule')('http://mysite:8080');
socket.on('connection', function connection(socket) {
socket.emit('message', {data:"test1"}); <====THIS WORKS
socket.on('init', function init(data) {
socket.emit('message', {data:"test1"}); <====THIS WORKS
refreshMyCustomModule();
});
});
var refreshMyCustomModule = function() {
socket.emit('message', {data:"test1"}); <=====THIS DOESN'T WORK
myCustomModule.beginSomeAsyncTask(function(data) { <======THIS DOESN'T WORK
socket.emit('message', {data:"test2"}); <========THIS DOESN'T WORK
});
};
Looking at the sample above. When I call my refreshMyCustomModule function suddenly socket and myCustomModule become undefined. I've also tried using this as well as setting up a var self = this.
I've written a bunch in javascript on the client but when coding in node.js it seems like scoping is different and I just can't crack this nut.
Note that the socket at the global level of your script and socket within your function connection are two different variables. The one inside your function connection is the argument that was passed into that function from the connection event. The one you're using in refreshMyCustomModule is the global one, the one on which you called listen.
This is clearer if we change their names, since they're different variables:
var socketio = require('socket.io');
var socketUsedForListen = socketio.listen();
var myCustomModule = require('./lib/mycustommodule')('http://mysite:8080');
socketUsedForListen.on('connection', function connection(socketFromConnection) {
socketFromConnection.emit('message', {data:"test1"});
socketFromConnection.on('init', function init(data) {
socketFromConnection.emit('message', {data:"test1"});
refreshMyCustomModule();
});
});
var refreshMyCustomModule = function() {
socketUsedForListen.emit('message', {data:"test1"});
myCustomModule.beginSomeAsyncTask(function(data) {
socketUsedForListen.emit('message', {data:"test2"});
});
};
I'm reasonably certain you meant to use socketFromConnection in refreshMyCustomModule, not socketUsedForListen. If so, either move the refreshMyCustomModule into your connection callback, or pass the socket into it as an argument.
It's because you're using an async event in socket.on('init') that leads to the scope issue. I believe if you pass in the parameters you want to use from the parent it will work. e.g.:
var socketio = require('socket.io');
var socket = socketio.listen();
var myCustomModule = require('./lib/mycustommodule')('http://mysite:8080');
socket.on('connection', function connection(socket) {
socket.emit('message', {data:"test1"}); <====THIS WORKS
socket.on('init', function init(data) {
socket.emit('message', {data:"test1"}); <====THIS WORKS
refreshMyCustomModule(socket, myCustomModule);
});
});
var refreshMyCustomModule = function(socket, module) {
socket.emit('message', {data:"test1"}); <=====THIS DOESN'T WORK
module.beginSomeAsyncTask(function(data) { <======THIS DOESN'T WORK
socket.emit('message', {data:"test2"}); <========THIS DOESN'T WORK
});
};

dnode server->client direct call possible? node.js

I use dnode
I have read StackOverflow: Send message from server to client with dnode
and undersand
dnode uses a symmetric protocol so either side can define functions that the opposing side can call.
as #substack the author replied.
So, right now, I have a code as the below:
server.js
var HTTPserver = httpServer('/www')
.listen(9999, function()
{
console.log('HTTP listening 9999');
});
var dnode = require('dnode');
var shoe = require('shoe')(
function(stream)
{
var TCPserver = require('net')
.createServer()
.listen(5005, function()
{
console.log('TCP listening 5005');
})
.on('connection', function(socket)
{
console.log('TCPsocket connected');
var d = dnode(
{
});
d.on('remote', function(remote)
{
remote.test();
});
d
.pipe(stream)
.pipe(d);
socket.end();
})
.on('end', function()
{
console.log('TCPsocket disconnected');
});
})
.install(HTTPserver, '/dnode');
client.js
var shoe = require('shoe');
var stream = shoe('/dnode');
var dnode = require('dnode');
var d = dnode(
{
test: function()
{
console.log('hello');
}
});
d.on('remote', function(remote)
{
console.log('connnected');
});
d.pipe(stream)
.pipe(d);
Basically, I want to call function:test -> hello initiated from server.
However, the result I see is
d.on('remote', function(remote)
{
console.log('connnected');
});
# client is evaluated.
d.on('remote', function(remote)
{
remote.test();
});
# server is never evaluated.
Why is that?
Of course, probably I can work around using client->server->client call back method, but if possible I just would like the straight forward way for my future work.
Thanks.
I found the answer which is simple enough, it is a bad idea to generate dnode d.on event definition in the TCP socket call back, since before dnode stuff is not there yet when it should triggered.

Categories