I am working on a socket.io + Node.js project.
When I print an variable using console.log, I get my variable on console.
But when I sent this variable to a client, it seems as [object Object] form on browser.
How can I see my variable on browser?
Thanks
Try console.log(JSON.stringify(myVariable)); and then look at it in your browser and you'll gain more insight as to what's happening exactly.
You may be using the 0.6 serverside syntax of:
socket.send({foo: 'bar'})
Try using the following updated syntax:
socket.json.send({foo: 'bar'})
You can find more information here:
https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7
thanks, console.log(JSON.stringify(myVariable)); worked for my case. Variable has shown as
{ coloumn_that_result_lays: "result"}. Of course we can overcome it with javascript-substring but is there a function which gives "result" directly.
// Require HTTP module (to start server) and Socket.IO
var io = require('socket.io'),
http = require('http');
io = require('socket.io');
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function (client){
//mysql
var mysql = require('db-mysql');
new mysql.Database({
hostname: 'localhost',
user: 'root',
password: '123123',
database: 'node'
}).connect(function(error) {
if (error) {
return console.log('CONNECTION error: ' + error);
}
this.query('SELECT data FROM exam where id=2 ').
execute(function(error,result) {
if (error) {
console.log('ERROR: ' + error);
return;
}
client.json.send(JSON.stringify(result));
});
});
// Create periodical which ends a message to the client every 5 seconds
var interval = setInterval(function() {
client.send('This is a message from the server! ' );
},1000);
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
Related
i have a console app, which connects to a server, prints output to the console.
here is the code made with Node js
var net = require('net');
var client = new net.Socket();
client.connect(port, 'ip', function() {
console.log('Connected');
client.write('enter password...');
});
client.on('data', function(data) {
console.log('Received: ' + data);
});
i can login successfully and read the output sent by the server on console based application, but i want to see these outputs on webpage. i tried using express but i have no clue how to use it.
app.get('/', function (req, res) {
client.on('data', function(data) {
res.send('<p>: ' + data + '</p>');
});
});
can anyone tell me where i am wrong? or should i use something else?
Server:
var net = require('net');
var stdin = process.openStdin();
var client_list = [];
var server = net.createServer(function(connection) {
//console.log('client connected');
connection.on('error', function(e){
if(e.code == 'ECONNRESET'){
console.log('Client dissconeccted');
}
});
//connection.write('Hello World!\r\n');
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
console.log("you entered: [" + d.toString().trim() + "]");
connection.write(d.toString().trim());
});
connection.pipe(connection);
});
server.listen(9999, function() {
console.log('server is listening');
});
Client:
var net = require('net');
var HOST = 'localhost';
var PORT = 9999;
//var client = new net.Socket();
var client = net.connect(PORT, HOST, function(){
console.log('connected to server! ' + HOST + ':' + PORT);
//client.write('I am Superman');
});
client.on('data', function(data) {
var data = data.toString();
console.log(data);
//If data starts with JS add injection functionallity
if (data === "END"){
client.end();
console.log("ENDING!")
}
else if (data === "poo"){
console.log("HOLY SHIT!")
}
});
//Keep trying to connect!
client.on('error', function(e) {
console.log('Parent connection error');
//client.end();
client.connect(PORT, HOST);
});
client.on('end', function() {
console.log('disconnected from server');
});
/*var client = net.connect({port: 8080}, function() {
console.log('connected to server!');
});*/
So what happens is that it keeps adding listeners(?) and warns me at 11 listeners with the message:
"Possible EventEmitter memory leak detected. 11 data listeners added.
Use emitter.setMaxListeners() to increase limit".
Why is this? I have tried fixing this by moving stdin.addListener() but it either doesn't take the input at all or the problem persists. Am I onto something? And how is code run in node, is it a loop?
Thanks in advance!
Have run both the client and server scripts. I can't reproduce the error message that you're getting. I'm running the code on Ubuntu - nodejs 6.9.5, npm 5.4.2. Could you post the contents of your package.json file?
Update: had a look online. seems like a known old bug in Node. https://github.com/nodejs/node-v0.x-archive/issues/5108
I have a simple and working web server written in NodeJS as below:
var http = require("http");
var fs = require("fs");
console.log("Web server started");
var config = JSON.parse(fs.readFileSync("./private/config.json"));
var server = http.createServer(function(req,res){
console.log("received request: " + req.url);
fs.readFile("./public" + req.url,function(error,data){
if (error){
// Not sure if this is a correct way to set the default page?
if (req.url === "/"){
res.writeHead(200,{"content-type":"text/plain"});
res.end("here goes index.html ?");
}
res.writeHead(404,{"content-type":"text/plain"});
res.end(`Sorry the page was not found.\n URL Request: ${req.url}`);
} else {
res.writeHead(200,{"content-type":"text/plain"});
res.end(data);
}
});
});
Now I want my web server to restart and listen to a new port when port number changes in the config file. So I add below code:
fs.watch("./private/config.json",function(){
config = JSON.parse(fs.readFileSync("./private/config.json"))
server.close();
server.listen(config.port,config.host,function(){
console.log("Now listening: "+config.host+ ":" +config.port);
});
});
This works fine and when I change the port on config file, I can access my web server on the new port. However, I also can access it on the previous port as well. I thought I am closing my web server on the previous port before I listen to the new port. What am I missing ?
I appreciate your help :)
As Mukesh Sharma mentioned, Server.close() stops accepting new connections and keeps existing connections. That is, server stays open for all alive sockets(until they naturally die due to keep-alive time) but no new sockets will be created.
I found out this question can be a possible duplicate of this question
So I followed the suggested solution mentioned by Golo Roden in the link and it worked. Basically you need to remember open socket connections and destroy them after you close the server. Here is my modified code:
var http = require("http");
var fs = require("fs");
console.log("Web server started");
var config = JSON.parse(fs.readFileSync("./private/config.json"));
var server = http.createServer(function(req,res){
console.log("received request: " + req.url);
fs.readFile("./public" + req.url,function(error,data){
if (error){
// Not sure if this the correct method ?
if (req.url === "/"){
res.writeHead(200,{"content-type":"text/plain"});
res.end("welcome to main page");
}
res.writeHead(404,{"content-type":"text/plain"});
res.end(`Sorry the page was not found.\n URL Request: ${req.url}`);
} else {
res.writeHead(200,{"content-type":"text/plain"});
res.end(data);
}
});
});
server.listen(config.port,config.host,function(){
console.log("listening: "+config.host+ ":" +config.port);
});
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
// Add a newly connected socket
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
// Remove the socket when it closes
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
});
fs.watch("./private/config.json",function(){
config = JSON.parse(fs.readFileSync("./private/config.json"))
console.log('Config has changed!');
server.close(function () { console.log('Server is closing!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
server.listen(config.port,config.host,function(){
console.log("Now listening: "+config.host+ ":" +config.port);
});
});
I'm missing something really basic here. I have two very standard express processes with socket io. I'm trying to get a server broadcast on one process to broadcast the same message to another servers clients. I have following setup:
var server = require('http').createServer(app);
var socketio = require('socket.io')(server, {
serveClient: (config.env !== 'production'),
path: '/socket.io-client'
});
require('./config/express')(app);
require('./routes')(app);
server.listen(config.port, config.ip, function () {
logger.info('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
var redis = require('socket.io-redis');
var adapter = redis({ host: config.redis.uri, port: config.redis.port });
adapter.pubClient.on('error', function(){
logger.error('Error on pub client');
});
adapter.subClient.on('error', function(){
logger.error('Error on sub client');
});
socketio.adapter(adapter);
require('./config/socketio')(socketio);
Then my socket io file is:
module.exports = function (socketio) {
//listen to other server broadcasts
socketio.on('socket.io#/#', function(data) {
logger.debug('received message from other process');
});
//client connection code
socketio.on('connection', function (socket) {
socket.address = socket.handshake.address !== null ?
socket.handshake.address + ':' + socket.handshake.address.port :
process.env.DOMAIN;
socket.connectedAt = new Date();
// Call onDisconnect.
socket.on('disconnect', function () {
onDisconnect(socket);
logger.debug('[%s] DISCONNECTED', socket.address);
});
// Call onConnect.
onConnect(socketio, socket);
logger.debug('[%s] CONNECTED', socket.address);
});
};
From a different server I'm just calling a standard emit
socketio.emit('message', object);
In terms of debugging, I load up the redis cli and check the channels that are created:
1) "socket.io#/#"
2) "socket.io-sync#request#/#"
I even run SUBSCRIBE "socket.io#/#" in the cli and can see the message I'm trying to get on the other server displayed via the cli.
This seems so basic, how do I properly subscribe to events on the redis channel 'socket.io#/#'?
EDIT: So I figured out that I receive messages on my other process if I do
socketio.sockets.adapter.subClient.on('message', function (channel, message) {
logger.warn('GOT STUFF ');
});
However here I'm just going straight to the redis sub client. The channel and message are just buffers of non usable data. Isn't this suppose to provide a higher level of abstraction?
EDIT 2: I've got it "mostly" working now. Doing this:
socketio.sockets.adapter.subClient.on('message', function (channel, message) {
logger.warn('GOT STUFF ');
socketio.sockets.in(channel).emit(message);
});
Turns on the socket interface will take the channel and message buffers directly. Now to my next issue, instead of doing socketio.emit(message, doc); I want to do this socketio.sockets.in(doc._id).emit('message;, doc);. Basically i only want it to end in clients that are a part of that room. Doesn't quite seem to be working as is...
Is it possible to connect to a NodeJS Server from another server? Two NodeJS servers communicating with each other?
//Server Code
var io = require('socket.io').listen(8090);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.sockets.emit('user disconnected');
});
});
//Client Code in Server Code. Connecting to another server.
io.connect( "http://192.168.0.104:8091" ); //Connect to another server from this one.
//ETC...
Here's a simple example that creates a server and a client that connects to that server. Remember that what you send has to be a buffer (strings are automatically converted to buffers). The client and server works independently of eachother, so can be put in the same app or on totally different computers.
Server (server.js):
const net = require("net");
// Create a simple server
var server = net.createServer(function (conn) {
console.log("Server: Client connected");
// If connection is closed
conn.on("end", function() {
console.log('Server: Client disconnected');
// Close the server
server.close();
// End the process
process.exit(0);
});
// Handle data from client
conn.on("data", function(data) {
data = JSON.parse(data);
console.log("Response from client: %s", data.response);
});
// Let's response with a hello message
conn.write(
JSON.stringify(
{ response: "Hey there client!" }
)
);
});
// Listen for connections
server.listen(61337, "localhost", function () {
console.log("Server: Listening");
});
Client (client.js):
const net = require("net");
// Create a socket (client) that connects to the server
var socket = new net.Socket();
socket.connect(61337, "localhost", function () {
console.log("Client: Connected to server");
});
// Let's handle the data we get from the server
socket.on("data", function (data) {
data = JSON.parse(data);
console.log("Response from server: %s", data.response);
// Respond back
socket.write(JSON.stringify({ response: "Hey there server!" }));
// Close the connection
socket.end();
});
The conn and socket objects both implement the Stream interface.
Check Substrack's dnode. It auto maps literal objects from the 1st env to the 2nd one. You gain a kind of RPC out of the box. And it works in the browser too...