socket io address gives ffff value - javascript

How do I get the address value(192.168.0.number) only, cause when I console the 'address' it gives me an additional value '::ffff:address'
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000, function() {
console.log('listening on *:3000');
});
app.use(express.static(__dirname + '/public'));
var usernames = {};
var numUsers = 0;
io.sockets.on('connection', function (socket) {
var addedUser = false;
var address = socket.handshake.address;
console.log("New connection from " + address);
}

That's an IPv4-mapped IPv6 address. I suppose the easiest way to extract the IPv4 portion would be to do something like:
// ...
var idx = address.lastIndexOf(':');
if (~idx && ~address.indexOf('.'))
address = address.slice(idx + 1);

Related

JavaScript for loop for object

I'm using Express to 'capture' data. I'm using a put request. My request is
localhost:3000/units/10 , with the body being:
{
"relayon0" : 400,
"relayoff0" : 400
}
And my code is:
var bodyParser = require('body-parser');
var mysql = require('mysql');
var express = require('express');
var app = express();
var conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'plc'
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.put('/units/:id', function(req,res){
var id = req.params.id;
var relayon = [];
var relayoff = [];
for(var i = 0; i < 8; i++){
relayon[i] = JSON.stringify(req.body.relayon + i);
relay[i] = JSON.stringify(req.body.relayoff + i);
}
res.send(relayon[0]);
});
app.listen(3000);
The response returns null.
Any ideas on what the issue is?
What you probably want is req.body['relayon' + i] and req.body['relayoff' + i].
Requesting req.body.relayon + i results in value of req.body.relayon (which is undefined) being added with number, which results with NaN. Being stringified, it results with "null".

socket io how to emit event to buddies?

Hi I'm making a chat with node js and I have a question. The chat is global, without rooms but users can only see and write to users in their buddy list. So when they connect to the server, they'll send also the user id and the buddy list as array. In the server I have a global variable with online users. Now, which is the best way to emit the event to users in the buddy list?
This is my current code:
var express = require('express');
var cors = require('cors');
var crypto = require('crypto');
var app = express();
var port = process.env.PORT;
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var socketio = require('socket.io');
var confdb = require('./lib/config-db.js');
var conf = require('./lib/config.js');
var db = require('./lib/chat-db');
var whitelist = [];
var secret_st = '';
var chrlimit = '';
var socketio_jwt = require('socketio-jwt');
var uidlist = {};
var id = {};
var mongodburl = process.env.MONGODB_URI;
// initialize db ===============================================================
mongoose.connect(mongodburl); // connect to our database
mongoose.Promise = global.Promise;
// set up our express application
confdb.findOne({'check': '1'}).exec(function(err, docs){
if (docs) {
whitelist = docs.origin;
secret_st = docs.spku;
chrlimit = docs.chrlimit;
if (docs.badwld) {
badwl = JSON.parse(docs.badwld);
}
} else {
conf.saveconfig();
}
startall();
});
function startall() {
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.use(cors(corsOptions), function(req, res, next) {
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// launch ======================================================================
var server = app.listen(port);
var io = socketio.listen(server);
//Routes ======================================================
app.get('/', function(req, res) {
res.writeHead(200);
res.end();
});
var nspm = io.of('/member');
nspm.use(socketio_jwt.authorize({
secret: secret_st,
handshake: true
}));
nspm.on('connection', function(socket) {
db.c_oneusr(socket.decoded_token, function(err, docs){
nspm.to(socket.id).emit('ckusr', 'ok');
initializeConnection(socket, 0);
});
});
function initializeConnection(socket, lstshout){
showActiveUsers(socket, lstshout);
}
function showActiveUsers(socket, lstshout){
socket.uid = socket.decoded_token.uid;
uidlist[socket.uid] = 1;
if (!id[socket.uid]) {
id[socket.uid] = {};
}
if (!msgtime[socket.uid]) {
msgtime[socket.uid] = [];
}
msgtime[socket.uid]['lpmsgt'] = lstshout;
id[socket.uid][socket.id] = 1;
socket.emit('login', {
uidlist: uidlist
});
// I need to change this and emit it only to buddies
socket.broadcast.emit('user joined', {
uidlist: uidlist,
uid: socket.uid
});
data = [];
data["uid"] = socket.decoded_token.uid;
data["id"] = socket.id;
data["buddies"] = socket.decoded_token.buddies;
db.updpml(data);
}
}

Sendgrid inbound webhook with node and multer

I'm trying to store emails from sendgrid via the inbound webhook using node, express and multer. There is an example on sendgrids site as below:
var express = require('express');
var multer = require('multer');
var upload = multer();
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(multer());
});
app.post('/parse', upload.array('files', 3) function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port %d', server.address().port);
});
This code throws an error when an email with an attachment is sent. The error is "unexpected field". I assume that the declaration for array.upload("files",3) is where the issue lies. Has anybody solved this?
You can solve this by using .any() when you don't the field name (see documentation for any()
Here's an example code
app.post('/parse', upload.any() function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});

NodeJS and SocketIO on Server

I have a problem with my NodeJS and SocketIO setup on my server,
I want to access the HTTP Port by doing
var socket = io.connect("http://domain.com:8070");
Sadly this returns ERR_CONNECTION_TIMED_OUT
Here is my Server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app, { log: false })
, fs = require('fs');
var mysocket = 0;
var socket = 0;
app.listen(8070);
function handler (req, res) {
fs.readFile(__dirname + '/app/tpl/skins/habbo/client.php',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('Client successfully connected');
mysocket = socket;
});
//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Packet recieved from server: " + msg);
if (mysocket != 0) {
mysocket.emit('field', "" + msg);
mysocket.broadcast.emit('field', "" + msg);
}
});
server.on("listening", function () {
var address = server.address();
console.log("udp server listening " + address.address + ":" + address.port);
});
server.bind(41181);
and my Client:
<script src="http://domain.com:8070/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect(http://domain.com:8070);
socket.on("hello", function(l){
var k = l.split(/,/);
switch(k){
case "testing":
{
window.alert('lol');
return;
}
}
});
</script>
Any ideas on how I can get it to work on http://domain.com:8070? Thanks.
It looks like your socket is not listening on port 8070.
Untested, but worth a try :
var io = require('socket.io').listen(app.listen(8070), {log: false});
You can also remove the URL from your client (although it shoudn't change anything) :
var socket = io.connect();
Edit :
You should also wrap the address in quotes :
var socket = io.connect("http://domain.com:8070");

Why doesn't emit event fire by socket.io

I'm using socket.io + express.
I want to emit 'start' and 'user_info' event to server from client. But it doesn't work. I wrote like this...
server.js
var express = require("express");
var http = require("http");
var socket = require("socket.io");
var app = express();
var ejs = require("ejs");
var server = http.createServer(app);
var io = require("socket.io").listen(server);
var redis = require("redis");
var _ = require("underscore");
require("./models/User");
app.get("/",function(req,res){
res.render("index",{});
});
socket.on("start",function(data){
console.log("Started");
});
socket.on("user_info",function(user_info){
var self = this;
var name = user_info.name;
var password = user_info.password;
user.name = name;
user.password = password;
var data = JSON.stringify({name: name,password: password});
});
### client.js
$(document).ready(function(){
var socket = io.connect("http://localhost:8080");
$("#register-btn").on("click",function(data){
$("#notice").html("Registerd");
var name = $("#name").val();
var password = $("#password").val();
var confirmPassword = $("#confirm-password").val();
if (name && (password === confirmPassword)){
// user_info event is works.
socket.emit("user_info",{"name": name,"password": password});
// I wonder why start event does not works.
socket.emit("start",{"name": "yahoo"});
}else{
$("#notice").html("try again");
}
});
});
I don't know why 'start' event is not being fired. Do you have any idea?
You are missing the connection part of Socket.io
// Noticed I removed the var socket = require('....
var io = require("socket.io").listen(server);
io.sockets.on('connection', function (socket) {
console.log('Client Connected')
socket.on("start",function(data){
console.log("Started");
});
socket.on("user_info",function(user_info){
var self = this;
var name = user_info.name;
var password = user_info.password;
user.name = name;
user.password = password;
var data = JSON.stringify({name: name,password: password});
});
});
You may want to read the docs # http://socket.io/

Categories