I am implementing a http server for some project.
I have an HttpServer object that I created that contains in it a server (net module)
this server contains allot of info, and i want to pass it as parameter to the callback functions. like you would do with "setTimeout"
var time=setTimeout(function(**a**){do somthing}, 2000, **someObject**);
I tried doing something like that in my code but it does not recognize the parameter I passed as an object
var net = require('net');
function HttpServer(port){
this.port=port;
}
HttpServer.prototype.start = function (){
console.log("starting the server");
this.server = net.createServer(function (socket,server) {
console.log("my port is: "+server.port)
socket.on('data',function(dat){ });
},this);
//i am trying to send to the createserver callback function
//the parameter 'this' that actually is an HttpServer
//and the callback function secives it as 'server'
//when i run the program i get an error that server is
//undefiend and therefor does not have a member port
this.server.listen(this.port);
}
var httpserver= new HttpServer(4444);
httpserver.start();
Why it does not recognize the parameter sent?
var net = require('net');
function HttpServer(port){
this.port=port;
}
HttpServer.prototype.start = function (){
console.log("starting the server");
var that = this; //Store this to that variable
this.server = net.createServer(function (socket, server) {
console.log('Server port is: ' + that.port); // Use that in an anonymous function
socket.on('data',function(dat){ });
});
this.server.listen(this.port);
}
var httpserver= new HttpServer(4444);
httpserver.start();
Related
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);
I used to use socket.io emit callback like following:
client:
mysocket.emit('helloword', 'helloword', function(param){
console.log(param);
});
server:
var server = require('http').Server(app);
var sserver = io(server);
sserver.on('connection', function(socket){
console.log('connection');
socket.on('helloword', function(message, callback){
console.log(message);
console.log(callback+'');
console.log('arguments', arguments);
callback('helloword');
})
});
server.listen(config.port);
I'm using angular-socket-io as a wrapper for socket.io-client. My service is simple as:
'use strict';
angular.module('core').factory('mysocket', function(socketFactory){
return socketFactory();
});
server output:
connection
helloword
function (){
// prevent double callbacks
if (sent) return;
var args = Array.prototype.slice.call(arguments);
debug('sending ack %j', args);
var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
self.packet({
id: id,
type: type,
data: args
});
}
arguments { '0': 'helloword', '1': [Function] }
My client console:
My question:
Why my callback is not firing ?
The function socket.on(event, callback) will listen for an event from the client and then run the callback when the event is triggered. In your case, when it hears 'helloword' it will run the callback function that you defined as the second parameter: function(message, callback). Your server log output shows that, actually, all of the console.log calls in your callback are being run.
To see what's going on client side try set the localStorage.debug = '*'
See this for more info: http://socket.io/docs/migrating-from-0-9/#log-differences (assuming you use socketio 1.0+)
I have the following code:
function Socket(io, playGame, mapper) {
io.on('connection', function (socket) {
// message handler for the chat message
socket.on('sendChat', function (data) {
console.log(socket);
console.log(data);
console.log('recieved chat');
var connectedPlayer = playGame.findConnectedPlayer(socket);
if (!connectedPlayer)
return;
var connectedGame = playGame.findConnectedGame(socket, connectedPlayer.gameId);
if (!connectedGame)
return;
// send update game with players properly ordered
for (socketIndex in this.sockets) {
var socket = this.sockets[socketIndex];
// send the new data to each player
socket.socket.emit('chatUpdate', { chatText: data.chat });
}
});
// message handler for join game message
socket.on('joinGame', function (data) {
console.log('recieved join:', JSON.stringify(data));
if (!playGame.newConnectedPlayer(socket, data))
return;
...
In the method for sendChat, socket is undefined. In the method for joinGame, socket is defined. I have tried several ideas, but the problem persists. Any help would be appreciated.
You'll have to rename one of the 2 socket variables -- either the parameter for 'connection' or the var in the loop:
io.on('connection', function (socket) {
for (socketIndex in this.sockets) {
var socket = this.sockets[socketIndex];
The var is shadowing the parameter, rendering the parameter inaccessible.
This happens in part because the var socket doesn't only exist within the for loop. JavaScript vars are function-scoped and their declarations are hoisted to the top of the function, as in:
socket.on('sendChat', function (data) {
var connectedPlayer, connectedGame, socket; // each initially `undefined`
console.log(socket);
// ...
for (socketIndex in this.sockets) {
socket = this.sockets[socketIndex];
// ...
});
And, having the same exact name, at most only one of them can be reached from a particular function.
Also note that the for loop and var socket aren't really necessary.
You can use the Socket.IO Server's own .emit() method to send a message to all clients.
io.emit('chatUpdate', { chatText: data.chat });
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.
Is it possible to run some script and if client connected pass arguments to it, something like this:
var io = require('socket.io').listen(http);
io.sockets.on('connection', function (client) {
console.log('Client connected');
var notifikacija = function (array) {
client.emit('populate', array);
}
});
///////////////////////////////////////////////////////////////////////
setInterval(function(){
var array = newArray();
array[0]='test';
notifikacija(array);
}, 2000);
Now it shows error: notifikacija is not defined. It is quite a strugle...
The notifikacija function is local to the scope of the io.sockets.on handler. You want it to be global so that you can access it in setInterval:
var notifikacija = function(){}; // just an empty function, in case it gets called before it has something to do
var io = require('socket.io').listen(http);
io.sockets.on('connection', function(client) {
console.log('Client connected');
notifikacija = function(array){ // once the client is available assign the function
client.emit('populate', array);
}
});
setInterval(function(){
var array = newArray();
array[0]='test';
notifikacija(array);
}, 2000);
Here's a blog post with some more information on scope in Javascript.