want to send javascript code to socket.io server - javascript

I want to send a javascript code to the socket.io server so that server broadcast to the clients and that code get executed .
what i tried i make a json variable like this .and send that via socket.io
var sent={
'code': function(){
console.log('javascript code');
}
};
socket.send(sent);
when i check at server the message comes is {} and same as it is to the other client .
what is wrong in this code , how should i send javascript code ?

Do not do this. You will open all listening clients to being hacked.
that said...
...you could follow pimbdb and pass the function in as a string, then use eval on the receiving end to execute it:
// on the sending client
var sent = {
"code": "function() { /* do something not evil */ }"
}
socket.send(sent);
// on the receiving client
socket.on('message', function(data) {
if (data.code) eval(data.code); // and pray.
});
Again, don't. Instead, pass some non-executable data that can then be interpreted in a limited number of non-malicious ways.
EDIT: Apologies, interpreted that as if you were executing code on the server. But client<-> client is XSS-prone, still.

Related

Are cookies the only way to give a client an instruction from a server to execute some js code?

Or in other words: How to send a client a message from a server to execute some js code on a page?
It is not an Ajax request, it is a plain GET browser-server request.
Let's say, I have this code in my app's front-end javascript file:
if( condition_1 ) {
FB.getLoginStatus(...)
}
else if( condition_2 ) {
PayPal.getLoginStatus(...)
}
else {
do smth else...
}
So I want to send those condition_1 or condition_2 instructions along with server's response. It is not Ajax request. It is a plain GET request from a browser to a server.
Only cookies are coming to my mind at the moment.
1) A server receives a GET request from a browser.
2) I read cookies. If there is no certain cookie came along with the request, I set condition_1, otherwise I set condition_2 cookie:
if(req.cookies["foo"] == "foo") {
res.cookies("foo", "condition_1")
.status(200)
.send()
.end();
}
else if(req.cookies["foo"] == "bar") {
res.cookies("foo", "condition_2")
.status(200)
.send()
.end();
}
3) A server sends a 200 response back to client.
Now in a browser I check those cookies (for the sake of simplicity I do document.cookie.foo):
if( document.cookie.foo == 'condition_1' ) {
FB.getLoginStatus(...)
}
else if( document.cookie.foo == 'condition_2' ) {
PayPal.getLoginStatus(...)
}
else {
do smth else...
}
And my question is, are cookies the only way in such a case? To instruct a client-side code to execute some condition
Cookies are stored in your browser and send back to the server with each request. It is for storing settings client side, not for sending info from the server.
If you are using some server side technology that can set cookies in the response then why not use it to send the script block you want executed back?
You are making things more complex they need to be: Javascript provides eval.
The server can simply reply a string with an expression/statement to evaluate in the browser context. It's not developed at the same level of say Lisp... but even in Javascript "data" can be "code" directly (without the need to raise the logical level by writing an interpreter like is instead required in languages like Java or C++).

Close mubsub client after emitting with socket.io-mongodb-emitter

I'm trying to emit some message into a socket.io room using socket.io-mongodb-emitter. My problem is that, my script never exists, because it keeps a connection alive to mongodb.
Please check my examples below, and give me some advice, how can I make the script close mongodb connection and let itself exit.
emitter.js this script emits the message, the client gets it, but the process doesn't exit.
var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
emitter-2.js this script exits, but the client never gets the message.
var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
io.client.close();
emitter-3.js this one works perfectly, the client gets the message, and the process exits. But setTimeout is an extremely bad solution, there must be some proper way to let this process exit by itself.
var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
setTimeout(function () {
io.client.close();
},100);
Maybe use a callback to get an acknowledgement that the client received the message, then call the close function
server:
var message = "hello";
io.in('someRoom').emit('someMessage', message, function(data){
console.log(data);
io.client.close();
});
client:
socket.on('someMessage', function(message, callback){
// do something with message here
callback('message received');
});
You need to use the .emit's ability to receive an acknowledgement that the message was sent.
Do like so:
io.in('someRoom').emit('someMessage',function(){
console.log('message was sent');
io.client.close();
);
On Server you need to call the function when it is received.
socket.on('someMessage', function (name, fn) {
fn('received');
});
Documentation here

Strophe Message Sent Acknowledgment Issue

I have implemented OPENFIRE with XMPP + BOSH on my Web based client interface.
When i am sending the message ,i check whether connection is live or not.If it is not live i create new connection and then send.
Sometimes it happens that client send a message and it is not get delivered to server(not opposite client).
So for that i need a strong thing that should inform client that this message didn't reach to server,please send again.
try { // sleep(2000);
Gab.connection.send(message); >
**var request = $msg({
to: jid,
"type": "get",
id: mid
}).c('get', {
'xmlns': Strophe.NS.DISCO_INFO,
'id': mid
});**
console.log(request); >
} catch (err) {
alert("Internet Disconnected ! Click ok to Reconnect SEND");
window.top.location.reload(1);
}
On above code i call message send().After that i call function as mentioned in "XMPP:xep-0184" doc.
but no response i received.
Thank you in advance.
Not sure what a "strong thing" is, but when someone is disconnected in Strophe, you should get errors from the script and it will update the Strophe.Status connection state. Strophe sends a post every 60 secs (unless otherwise specified). In your code it appears you're trying to check support.
You should look for "Strophe.Status.CONNECTED" or "Strophe.Status.ATTACHED" prior to sending if that's your concern. You can also write a handler to manage the errors.
In XEP 0184, you must include:
<request xmlns='urn:xmpp:receipts'/>
So your msg should look like (note, you must include an id per XEP 0184):
$msg({
to: tojid,
from: fromjid,
type: "chat",
id: "sometrackingid"}).c('body').t("bodytxt").up().c("request", {
xmlns: "urn:xmpp:receipts"});
You will then need to modify you message handler or create a separate handler to manage the receipts.

Sockets server2server connection

Sockets unlike HTTP doesn't have anything that is req, res it is always like:
client.on('data', function(data)...
Event gets executed when there is data on the stream.
Now I want to do a Server 2 Server communication. I'm writing a game where I am gonna have a main server and this main server communicates with the games desktop client.
One server is a World server and the other is a Login server. The client directly connects to the world server and if the data is a login data then the world server passes it to the login server.
But I cant wrap my head around how to do this in node. As a previous webdev I can only think of:
login.send(dataToSendToOtherServer, function(responseOfOtherServer) {
if (responseOfOtherServer === 1)
client.write(thisDataIsGoingToTheDesktopClient)
})
So how can I do something like this for the sockets in node.js?
I tried something like:
Client.prototype.send = function(data, cb) {
// convert json to string
var obj = JSON.stringify(data)
this.client.write(obj)
// wait for the response of this request
this.client.on('data', function(req) {
var request = JSON.parse(req)
// return response as callback
if (data.type === request.type) cb(request)
})
}
But with this every request the response gets +1.
Since you're dealing with plain TCP/IP, you need to come up with your own higher-level protocol to specify things like how to determine when a message is complete (since TCP offers no guarantee it will all arrive in one gulp). Common ways of dealing with this are:
Fixed-length messages: buffer up received data until it's the right length.
Prefixing each message with a length count: buffer up received data until the specified length has been reached.
Designating some character or sequence as an end-of-message indicator: buffer up received data until it ends with that sequence/character.
In your case, you could buffer up received data until JSON.parse succeeds on the accumulated data, assuming each message consists of legal JSON.

Passing Function from Server to Client

for a recent project of mine I need to pass two functions from my server (written in node.js) to a client javascript tag. Actually to be completly correct, the client side javascript calls an XML request and I want to return some data and two functions for him which he should be able to use.
Second thing is I want to store a javascript function into a database in the server and then fetch it if the client requests it.
Anyone knows how this can be archieved and has some experience with it?
Note: you should really consider doing this in an HTTPS connection.
OK, so you want to receive code from the server and run it on the client. You could inject a script tag to the body and let the browser execute it. However, since you trust the code. I would simply use an eval call since that's what you'll doing anyway.
Here's how it would look in an Express app:
// server
function hello() {
alert('hello');
}
app.get('/get/js/code', function (req, res) {
res.send({
code: hello.toString(),
start: 'hello()'
});
});
// client (with jQuery)
$(function () {
$.getJSON('/get/js/code', function (json) {
eval(json.code + ';' + json.start + ';');
});
});

Categories