Why does socket.io now give 500 (Internal Server Error) with express.io??
client side:
$(document).ready(function(){
$.getScript("http://www.mysite.com:8000/socket.io/socket.io.js",function(){
var socket = io.connect('http://www.mysite.com:8000'); //<<--error
socket.emit('ready');
});});
server side:
var express = require('express.io')
, engine = express().http().io();
engine.use(express.cookieParser());
engine.use(express.session({secret:'monkey'}));
engine.all('/',function(req,res,next){res.header("Access-Control-Allow-Origin","*");res.header("Access-Control-Allow-Headers","X-Requested-With");next();});
engine.get('/', function(req, res) {
req.session.loginDate = new Date().toString()
res.sendfile(__dirname)
});
engine.listen(8000);
engine.io.route('ready',function(socket){console.log('hellooooooooooo');});
I am following the docs on https://github.com/techpines/express.io, I have only changed two things: cross domain and app is called engine instead. I just can't see the problem Has anyone else got this to work?
Note: it's not using express.js it's using express.io (more compatable with socket.io)
It's like socket.io is not their listening on the server even though engine = express().http().io(); io is socket.io
I faced a similar problem, but I fixed it by copying and pasting the code sample in express.io sample code, and it worked. Then I compared them to check what the problem could be and observed that order of the code matters.
This order results in an error:
static
cookieParser
session
But when I followed the code provided in the sample code, I found out that this order works:
cookieParser
session
static
Hopefully this will also help you.
I believe the posted example is failing because you're using the call res.sendfile(__dirname) without supplying a filename.
This is coming from express.io, notice it uses res.sendfile(__dirname + '/client.html'):
express = require('express.io')
app = express().http().io()
// Setup your sessions, just like normal.
app.use(express.cookieParser())
app.use(express.session({secret: 'monkey'}))
// Session is automatically setup on initial request.
app.get('/', function(req, res) {
req.session.loginDate = new Date().toString()
res.sendfile(__dirname + '/client.html')
})
Related
I'm currently developing a webOS TV application which includes a background running service. I'm having trouble getting logs to print in the NodeJS console.
I have no prior experience working with Node so I'm unsure whether any additional modules are required to get this done(but I highly doubt it, and the docs don't seem to suggest so.)
As of now my service side code is as follows;
var Service = require('webos-service');
var service = new Service("com.nuwan.helloworld.service");
// code to keep the service from being terminated
var keepAlive;
service.activityManager.create("keepAlive", function(activity) {
keepAlive = activity;
});
service.activityManager.complete(keepAlive, function(activity) {
console.log("completed activity");
});
// hello command implementation
service.register("hello", function(message) {
var response = message.respond({
data: "Hello, " + message.payload.name + "!"
});
});
It would be great if someone could give me some pointers.
As it is right now, I'm not getting any output whatsoever on the Node Profiler console.
The way i did it ( i don't know if that's the only way) to debug the code is through the chromium debugger eg.
This is a generic image to see from where you are going to check the code.
const TeleBot = require('telebot');
const bot = new TeleBot({
token: 'i9NhrhCQGq7rxaA' // Telegram Bot API token.
});
bot.on(/^([Hh]ey|[Hh]oi|[Hh]a*i)$/, function (msg) {
return bot.sendMessage(msg.from.id, "Hello Commander");
});
var Historiepics = ['Schoolfotos/grr.jpg', 'Schoolfotos/boe.jpg',
'Schoolfotos/tobinsexy.jpg'];
console.log('Historiepics')
console.log(Math.floor(Math.random() * Historiepics.length));
var foto = Historiepics[(Math.floor(Math.random() * Historiepics.length))];
bot.on(/aap/, (msg) => {
return bot.sendPhoto(msg.from.id, foto);
});
bot.start();
The result I'm getting from this is just one picture everytime, but if I ask for another random picture it keeps showing me the same one without change.
I recently figured this out, so I'll drop an answer for anyone that runs into this issue.
The problem is with Telegram's cache. They cache images server side so that they don't have to do multiple requests to the same url. This protects them from potentially getting blacklisted for too many requests, and makes things snappier.
Unfortunately if you're using an API like The Cat API this means you will be sending the same image over and over again. The simplest solution is just to somehow make the link a little different every time. This is most easily accomplished by including the current epoch time as a part of the url.
For your example with javascript this can be accomplished with the following modifications
bot.on(/aap/, (msg) => {
let epoch = (new Date).getTime();
return bot.sendPhoto(msg.from.id, foto + "?time=" + epoch);
});
Or something similar. The main point is, as long as the URL is different you won't receive a cached result. The other option is to download the file and then send it locally. This is what Telebot does if you pass the serverDownload option into sendPhoto.
i've currently started using sailsJS with angularJs at frontend alognwith socket for realtime communiction.
Sailsjs gives built-in support to websocket through "sails.io.js".On client side after adding this library this code is added to angular's chat controller.
Client side code
io.socket.get('/chat',{token:token},function(users){
console.log(users);
});
chatController's action on sails side is like this.
Server side code
chat: function (req, res) {
console.log(req.isSocket);
//this gives true when called through client.
})
infact very new to sails so i want suggestion that how to maintain connected user's list because m not using redis as storage purpose.adapter is memory.array is not a good idea because it'll vanish when restart a server.m using sails version of 0.11.0.
thanx in advance.
I'm somewhat new but learning fast, these suggestions should get you there unless someone else responds with greatness...
They changed it in 11 but in 10.5 I use sockets.js in config folder and on connect I store the session data in an array with their socket.
I created a service in APIs/service that contains the array and socket associate function.
For v11 you can't do that exactly the same, but you can make your first 'hello' from the client call a function in a controller that calls the associate function.
A couple tips would be don't let the client just tell you who they are, as in don't just take the username from the params but get it from req.session
(This assumes you have user auth setup)
In my case I have
in api/services/Z.js (putting the file here makes it's functions globally accessible)
var socketList = [];
module.exports = {
associateSocket: function(session, socket) { // send in your username(string) socket(object) id(mongoId) and this will push to the socketlist for lookups
sails.log.debug("associate socket called!",socketList.length)
var iHateYou = socketList
//DEBUG
var sList = socketList
var util = require('util')
if (session.authenticated){
var username = session.user.auth.username
var userId = session.user.id
// sails.log.debug("Z: associating new user!",username,userId,socket)
if (username && socket && userId) {
sList[sList.length]= {
username: session.user.auth.username,
socket: socket,
userId: session.user.id,
};
sails.log.debug('push run!!! currentsocketList length',socketList.length)
} else sails.log("Z.associateSocket called with invalid data", username, userId, authId, socket)
}else{sails.log.warn("Z.associateSocket: a socket attempted to associate itself without being logged in")}
},
}
in my config/sockets.js
onConnect: function(session, socket) {
Z.associateSocket(session,socket)
if (session.user && session.user.auth){
sails.log("config/sockets.js: "+session.user.auth.username+" CONNECT! session:",session)
}else sails.log.warn('connect called on socket without an auth, the client thinks it already has a session, so we need to fix this')
// By default, do nothing.
},
Then you can make add some functions to your services file to do lookups based on username and passwords, remove sockets that are disconnecting and the like (I'm using waterlock for my auth at the moment, although debating the switch back to sails-generate-auth)
Remove your onConnect and dicconnect function from config/sockets.js.
Trying to figure out how to use the MS Translator API to use the MS Translator but running into problems.
I don't have the ability to serve up a Node, PHP or other server to securely provide the ClientID or ClientSecret at this time so I'm trying to do it simply with straight HTML and Javascript for now.
I'm trying to use this AJAX as recommended by MS API but I believe this is looking for the server to provide the authentication. Looking for help to figure out how to right this with HTML/JS without the server side authentication. Thanks!
function translate() {
var from = "en", to = "es", text = "hello world";
var s = document.createElement("script");
s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
"?appId=" + settings.appID +
"&from=" + encodeURIComponent(from) +
"&to=" + encodeURIComponent(to) +
"&text=" + encodeURIComponent(text) +
"&oncomplete=mycallback";
document.body.appendChild(s);
}
function mycallback(response) {
alert(response);
}
Try using appId=8B841CA7C1A03443682C52AD07B7775A7BD5B3AA
This works fine for me, I found that on the other thread. Sorry if this is not what you are looking for. I have to admit the authentication is the difficult part, I even tried using the script found at the MDSN page on translate, http://msdn.microsoft.com/en-us/library/ff512406.aspx
I couldn't comment with my 26 rep points, so I am writing here as my answer. Thanks.
So I'm building a multipart form uploader over ajax on node.js, and sending progress events back to the client over socket.io to show the status of their upload. Everything works just fine until I have multiple clients trying to upload at the same time. Originally what would happen is while one upload is going, when a second one starts up it begins receiving progress events from both of the forms being parsed. The original form does not get affected and it only receives progress updates for itself. I tried creating a new formidable form object and storing it in an array along with the socket's session id to try to fix this, but now the first form stops receiving events while the second form gets processed. Here is my server code:
var http = require('http'),
formidable = require('formidable'),
fs = require('fs'),
io = require('socket.io'),
mime = require('mime'),
forms = {};
var server = http.createServer(function (req, res) {
if (req.url.split("?")[0] == "/upload") {
console.log("hit upload");
if (req.method.toLowerCase() === 'post') {
socket_id = req.url.split("sid=")[1];
forms[socket_id] = new formidable.IncomingForm();
form = forms[socket_id];
form.addListener('progress', function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
});
form.parse(req, function (err, fields, files) {
file_name = escape(files.upload.name);
fs.writeFile(file_name, files.upload, 'utf8', function (err) {
if (err) throw err;
console.log(file_name);
})
});
}
}
});
var socket = io.listen(server);
server.listen(8000);
If anyone could be any help on this I would greatly appreciate it. I've been banging my head against my desk for a few days trying to figure this one out, and would really just like to get this solved so that I can move on. Thank you so much in advance!
Can you try putting console.log(socket_id);
after form = forms[socket_id]; and
after progress = (bytesReceived / bytesExpected * 100).toFixed(0);, please?
I get the feeling that you might have to wrap that socket_id in a closure, like this:
form.addListener(
'progress',
(function(socket_id) {
return function (bytesReceived, bytesExpected) {
progress = (bytesReceived / bytesExpected * 100).toFixed(0);
socket.sockets.socket(socket_id).send(progress);
};
})(socket_id)
);
The problem is that you aren't declaring socket_id and form with var, so they're actually global.socket_id and global.form rather than local variables of your request handler. Consequently, separate requests step over each other since the callbacks are referring to the globals rather than being proper closures.
rdrey's solution works because it bypasses that problem (though only for socket_id; if you were to change the code in such a way that one of the callbacks referenced form you'd get in trouble). Normally you only need to use his technique if the variable in question is something that changes in the course of executing the outer function (e.g. if you're creating closures within a loop).