Node.js Socket.io socket.brodcast is undefined - javascript

brodcast.emit to send a message to all without socket, and when I do that the node instance crashes and says that socket.brodcast is undefined .
here is my node code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
io.on('connection', function(socket){
socket.on("newChild",childData =>{
var newChildID = mainData.newChild(childData.fatherID,childData.data, childData.type);
socket.emit("newChildID",{ "newId" : newChildID,"old" : childData.localID});
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
});
});
when I emit "newChild" from the client the server crashes and say that socket.brodcast is undefined
The important part is to get socket.brodcast.emit , so do I use the API wrong?
when I googled after it I found this: Send response to all clients except sender (Socket.io)
In this thread I found this example:
socket.on('cursor', function(data) {
socket.broadcast.emit('msg', data);
});
And its seams to be the same as i do.

your code contains a typo for starters...
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
should be
socket.broadcast.emit("newChild",maindata.getDataPoint(newChildID));

Related

Node.js + Socket.io: Unable to set ping timeout

In my Node.js + Socket.io application, I'm trying to set the ping timeout to 63 seconds (63 seconds of inactivity allowed until the connection between the server and the client(s) is considered closed). Unfortunately, when I run my code below, I get the following error:
var io = socket(server);
^
TypeError: socket is not a function
Below is my code:
var express = require("express");
var socket = require("socket.io")(3000, {
pingTimeout: 63000,
});
var app = express();
var server = app.listen(3000);
app.use(express.static("public"));
var io = socket(server);
just remove this line
var socket = require("socket.io")(3000, { pingTimeout: 63000, });
and try adding this in io variable
var io = require("socket.io")(server, {pingTimeout: 63000, });

combining functionality of two Node servers with different initial set up

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?
You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

How to get details of the user that sent data (.emit()) to nodejs server?

I'm experimenting on an app that is running with nodejs, express and socket.io
Server Side:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.on('send_stuff', function(stuff){
io.emit('log_stuff',newStuff);
});
});
http.listen(54123, function(){
console.log('listening on *:54123');
});
Client Side:
var socket = io.connect('http://example.com:12345');
socket.emit('send_stuff',stuff);
My question is How do I get the details of the client (ip,user-agent,etc.) that executed socket.emit('send_stuff',stuff)?
I want to pass it to the newStuff variable.
socket.on('send_stuff', function(stuff){}); in this line stuff only returns the value that was send by client emit().
Any ideas how to do this?
You can get client's ip and user-agent in connection event.
io.on('connection', function(socket){
console.log("ip: "+socket.request.connection.remoteAddress);
console.log("user-agent: "+socket.request.headers['user-agent']);
})
Documentation can give you some hints http://socket.io/docs/server-api/
This worked for me:
io.on('connection', function(socket) {
var userAgent = socket.handshake.headers["user-agent"];
console.log("User-Agent: " + userAgent);
});

socket.io connection not heppening

This is first time, I am using socket.io.I stuck at initial stage itself.sorry it's may be simple question.
server side code :
Inside my server.js I written the following code.
var express = require('express')
,io=require('socket.io')
,http = require('http')
var app = express();
server = http.createServer(app);
io = io.listen(server,{ log: false });
Now I trying to make connection inside server.js file,like in the following way.
io.sockets.on('connection', function (socket) {
console.log("This is testing");
io.to(socket.id).emit('notification', 'for your eyes only');
});
client side code :
var socket = io.connect("http://localhost");
socket.on('connect', function () {
console.log("connect")
});
socket.on('notification', function (data) {
console.log(data);
});
I open application in browser, as per my code it suppose to console connect statement but it's not happening.
my server is running on port no :80Where am I did wrong, can anyone help me.
Thanks.
Here is the working code for me in express it may help you.
var express = require('express')
, app = express()
, server = require('http').Server(app)
, io = require('socket.io')(server)
var defaultPort = 6001 ;
server.listen(defaultPort, function() {
console.log('Server Started');
});
io.sockets.once('connection', function(socket) {
return io.sockets.emit('new-data', {
channel: 'stdout',
value: "Your Data Goes Here"
});
socket.on('disconnect', function(){
});
});
On Client Side
<script>
$(function() {
var socket = io.connect('http://localhost'); //if you are trying on server put server url if you are working on local then use localhost
socket.on('new-data', function(data) {
$('#YouDivid').html(data.value);
});
});
</script>

Socket.io 400 (Bad Request)

I have this piece of code on my server
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.sockets.on('connection', function (socket) {
console.log("Socket connected");
});
I just want to create a connection
and on the client -
<script src="public/javascripts/socket.io.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
</script>
And when I open my browser I get this error in console:
GET http://127.0.0.1:3000/socket.io/1/?t=1404410309733 400 (Bad Request) socket.io.js:1659
XHR finished loading: GET "http://127.0.0.1:3000/socket.io/1/?t=1404410309733".
I've already done this like 10 times and I never get this. Does anyone know how to fix it?
I think an older version of socket-io could be the reason.
I was getting this problem when I was using 0.9.16 version. I upgraded to following and it worked.
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>

Categories

Resources