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.
Related
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.
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..
I've got an Adobe AIR Application on the local machine that communicates with an remote node.js server script (socket-script.js) via socket connection.
Furthermore i start a new node.js process through command line and send some additional arguments to a second server script (terminal-script.js).
Question: How can i send the arguments from the terminal-script.js to socket-script.js? Afterwards the socket-script.js should broadcast the
args to the AIR Application. Anyone an idea how to connect the two independent running processes in Node.js? Thanks.
Illustration link
Use the server to communicate between processes:
socket-script.js
var net = require('net');
var app = null;
var server = net.createServer(function(socket) {
socket.on('data', function(data){
if(data.indexOf('terminal:') >-1){
if(app){
app.write(data);
}
} else if(data.indexOf('app:') >-1){
app = socket;
}
});
});
terminal-script.js:
var net = require('net');
var client = net.connect({port: 9001}, function() {
client.write('terminal:' + process.argv[2]);
});
app:
var net = require('net');
var client = net.connect({port: 9001}, function() {
client.write('app:connect');
});
client.on('data', function(data){
if(data.indexOf('terminal:') >-1){
// got terminal data
}
});
The only way that I conceive of to make this work is something like this:
1) You'll need to have terminal-script.js be listening on a socket. Like so:
var arguments = process.args.splice(2);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(arguments[0]);
}).listen(8000, '127.0.0.1');
2) Just make a request from socket-script to the terminal script:
//somewhere in socket-script use this to grab the value from the terminal script.
var http = require('http');
var options = {
host: 'terminal-script-host.com',
port: '8000',
path: '/'
};
var req = http.get(options, function(res) {
res.on('data', function (data) {
console.log('socket-script got the data from terminal-script: ' + data);
});
});
Not sure if this helps. But I can tell you that it would be nearly impossible to "inject" something into the socket-script from the terminal-script, not in a way that would work with the same request anyways.
I am a trying to use socket.io and node.js like this :
The browser sends an event to socket.io, in the data event I call another server to get some data, and I would like to send back a message to the browser using a socket.emit.
This looks like that :
socket.on('ask:refresh', function (socket) {
const net = require("net");
var response = new net.Socket();
response.setTimeout(1000);
response.get_response = function (command, port, host) {
this.connect(port, host, function () {
console.log("Client: Connected to server");
});
this.write(JSON.stringify({ "command": command }))
console.log("Data to server: %s", command);
};
response.on("data", function (data) {
var ret = data.toString();
var tmp_data = JSON.parse(ret.substring(0, ret.length - 1).toString());
var data = new Object();
var date = new Date(tmp_data.STATUS[0].When * 1000 );
data.date = date.toString();
socket.emit('send:refresh', JSON.stringify(data) );
});
response.get_response("version", port, host);
});
};
The thing is that I cannot access "socket.emit" inside response.on.
Could you please explain me how I can put a hand on this ?
Thanks a lot
You appear to be overwriting the actual socket with the one of the callback parameters:
socket.on('ask:refresh', function(socket) {
// socket is different
});
Change the name of your callback variable, and you won't have this problem.
I'm trying to create a basic game (only text) using Node.js, and it's 'net' library.
I'm hitting a bit of a wall. I can't seem to figure out how to prompt the user to enter some information, and wait for the user to enter said information.
Here's the code I have so far. It's fairly basic, and will print out 2 lines for you when you run the client, and then hang. It's at that point I want the user to be able to enter information. I'm unsure of a few things here:
1. How do I enable the user to type? (more specifically, is it client or server side)
2. How do I send that data to the server when enter is pressed?
I have read up on some documentation as far as Telnet goes, and it leads me to my last question: is the Telnet module in Node really the right one for this, or is there a better alternative for client/server creation and communication?
Client Code:
var connect = require('net');
var client = connect.connect('80', 'localhost');
console.log('Connection Success!\n\n');
client.on('data', function(data) {
// Log the response from the HTTP server.
console.log('' + data);
}).on('connect', function() {
// Manually write an HTTP request.
//I'm assuming I could send data at this point here, on connect?
}).on('end', function() {
console.log('Disconnected');
});
Server Code:
var net = require('net');
var sockets = [];
function cleanInput(data) {
return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}
function receiveData(socket, data) {
var cleanData = cleanInput(data);
if(cleanData === "quit") {
socket.end('Goodbye!\n');
}
else {
for(var i = 0; i<sockets.length; i++) {
if (sockets[i] !== socket) {
sockets[i].write(data);
}
}
}
}
function closeSocket(socket) {
var i = sockets.indexOf(socket);
if (i != -1) {
sockets.splice(i, 1);
}
}
function newSocket(socket) {
sockets.push(socket);
socket.write('Welcome to the Battleship Server!\n\n');
socket.write('Please enter a username: ');
socket.on('data', function(data) {
receiveData(socket, data);
})
socket.on('end', function() {
closeSocket(socket);
})
}
var server = net.createServer(newSocket);
server.listen(80);
Thanks in advance!
you want to use process.stdin and process.stdout to interact with input/output from/to the terminal. Have a look here.
You can send data to the server when enter is pressed with process.stdin.once('data', function(data){ /* ... */ }). The .once method ensures that the callback is called just once when the user hits enter.
The client code should look like:
var connect = require('net');
var client = connect.connect('80', 'localhost');
client.on('data', function(data) {
console.log('' + data);
process.stdin.once('data', function (chunk) {
client.write(chunk.toString());
});
}).on('connect', function() {
client.write('Hello');
}).on('end', function() {
console.log('Disconnected');
});