I am having trouble launching my Node app. I get "TypeError: Cannot call method 'push' of undefined" error.
Here is my code:
spdy.createServer(credentials, app).listen(app.get('port'), function(req, res) {
res.push('public/js/bootstrap.min.js', {'content-type': 'application/javascript'}, function(err, stream) {
stream.end('alert("hello from push stream!")');
});
res.push('public/js/jquery.min.js', {'content-type': 'application/javascript'}, function(err, stream) {
stream.end();
});
res.push('public/css/bootstrap.min.css', {'content-type': 'text/css'}, function(err, stream) {
stream.end();
});
// write main response body and terminate stream
res.end('Hello World!');
console.log('Express HTTPS SPDY server listening on port ' + app.get('port'));
} );
I am running SDPY version 1.19.2 and NodeJS version 0.10.25.
Based on your comment, you are serving with HTTP/1.1. You need to be serving with HTTP2/SPDY for push to work.
Try this:
// set the root path of Express server
app.use(express.static(__dirname+'/public');
app.use(function(req, res) {
// your res.push code is here.
var stream = res.push('/js/bootstrap.min.js', {'content-type': 'application/javascript'});
stream.on('acknowledge', function() {
console.log('stream ACK');
});
stream.on('error', function() {
console.log('stream ERR');
});
stream.end('alert("stream SUCCESSFUL");');
res.end('<script src="/js/bootstrap.min.js"></script>');
});
spdy.createServer(credentials, app).listen(app.get('port'));
The callback function passed to listen() function takes no arguments. see line 49, file stream-test.js
Related
I have a HTTP server that will always result in HTTP timeout, e.g.
const server = http.createServer((req, res) => {
setTimeout(() => {
res.writeHead(200);
res.write('OK');
res.end();
}, 2000);
});
server.setTimeout(1000);
server.on('timeout', (socket) => {
// How to produce a custom HTTP response here?
});
HTTP server "timeout" event is emitted with socket reference. How do I use socket to encode HTTP response?
I know that I can stitch the response myself at a low-level, e.g.
server.on('timeout', (socket) => {
socket.write([
'HTTP/1.1 408 Request Timeout',
'Connection: close'
].join('\n') + '\n\n');
socket.end();
});
But is there a way to use the HTTP response interface, i.e. writeHead/ write/ end?
You could use the setTimeout function on the response object. Consider this simple example:
const http = require('http');
const port = 3000;
const requestHandler = (req, res) => {
res.setTimeout(Math.random() * 2500, () => {
res.writeHead(408);
res.end();
});
setTimeout(() => {
if (res.headersSent) {
return;
}
res.writeHead(200);
res.write('OK');
res.end();
}, 2000);
};
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('an error happened', err)
}
console.log(`server is listening on ${port}`)
});
If you call localhost:3000 in your web browser you'll now either see 200 OK or a 408 error. Note that you'll need to handle already sent headers if the random timeout was less than 2000 ms.
I'm trying to setup some socket.io communications, the communication between my server (app.js)(runs on a raspberry pi) and a website(public/index.html) works fine. Now I want to expand it so when my app.js receives a call from index.html it emits it further to another node.js script(bed.js) that will run on another raspberry pi. I tried to use the npm module socket.io-client, but this can only receive apparently
!edit! problem has narrowed down to the setrgb part, there it won't emit.
!edit 2! when i receive setRGB, i emit setRGBclient, but that can only be received in bed.js, not in index.html, there lays my problem, i need to share the connections or force it to another connection, no clue how i fix it though
APP.JS:
let http = require('http').createServer(handler); //require http server, and create server with function handler()
let fs = require('fs'); //require filesystem module
let io = require('socket.io')(http) //require socket.io module and pass the http object (server)
let delay = require('delay');
console.log('Define each color from RGB Strip light.');
http.listen(8080); //listen to port 8080
function handler (req, res) { //create server
fs.readFile(__dirname + '/public/index.html', function(err, data) { //read file index.html in public folder
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {// WebSocket Connection
socket.on("test", function(){
console.log("sampletext");
});
socket.on("setRGB", function(data){
socket.emit("setRGBClient", data);
console.log(data);
console.log("test");
});
});
bed.js:
let socket = require('socket.io-client')('http://localhost:8080');
let lightstate = false;
let stayOff = false;
let fadeState = false;
console.log("check");
socket.emit("test");
socket.on("setRGBClient" ,function(data) {
console.log(data);
});
I can just broadcast setRGBClient.
socket.broadcast.emit("setRGBClient", data);
I guess this is a learning exercise. Otherwise I’d caution against socket.io for such applications.
However I can only see the subscription for ‘setRGB’ not the emit-part.
I'm developing a server with Node JS where I create multiple childs that open a html with chrome.
app.post('/exeVideo', function(req,res) {
child = child_process.spawn('chromium-browser', ['RaspMediaVideos.html']);
child.on('exit', function() {
res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
res.end();
});
});
This Html has a socket.io communication with the server:
io.on("connection", function ( socket ){
app.post('/playVideo', function(req,res) {
socket.emit("playvideo");
res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
res.end();
});
app.post('/pauseVideo', function(req,res) {
socket.emit("pausevideo");
res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
res.end();
});
My problem here is that if I create 2 childs_process with the code showed above, both chrome windows executes well but only the first one is taking the socket.io events (works good). The second one don't respond to any event :S How can I make it to make ALL childs capture the socket.io events?
Here's the script of html handling events:
var socket = io.connect('http://localhost:3434');
socket.on("pausevideo", function() {
player.pause();
});
socket.on("playvideo", function() {
player.play();
});
Thanks for your time.
You're calling socket.emit in those functions which will only send to the calling socket. Try something like this instead.
app.post('/playVideo', function(req,res) {
io.sockets.emit("playvideo");
res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
res.end();
});
app.post('/pauseVideo', function(req,res) {
io.sockets.emit("pausevideo");
res.writeHead(200,"0K",{'Content-Type': 'text/plain'});
res.end();
});
io.on("connection", function (socket) {
// Handle Events
}
So I have the following code -
var http = require('http');
http.createServer(function (req, res) {
console.log("Connected!");
res.writeHead(200);
req.on('data', function(data) {
res.write(data);
});
}).listen(5000);
But when I write into chrome localhost:5000 it just load the page, and then it says that the server didn't sent any data..
I figured out that If I write req.end(); after the data event, it loads the page perfectly. However, I don't want to end the request immediately.
What should I do?
You'll have to call res.end() at some point, but you can wait for the req to 'end' first:
req.on('end', function () {
res.end();
});
I am completely new to the socket.io and trying to get my feet wet by starting with examples on their home page. But all that i get in console after execution is this
debug - served static content /socket.io.js
My Server side code is this:
var app=require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res)
{
fs.readFile(__dirname + '/index.html', 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("connected");
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
})
And my index.html goes like this:
var socket = io.connect('document.location.href');
socket.on('error',function(reason){
// console.error("Error");
});
socket.on('connect', function () {
console.log('connected');
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>
I googled about it and couldn't resolve the issue. I am on ubuntu with firefox.
If i'm not mistaken your error is here:
'document.location.href'
which shall be
document.location.href
I've just complete a simple example app for which I'll be soon writing a tutorial:
https://github.com/dotcloud/socket.io-on-dotcloud
You can grab it (just clone it) and fool around with it to easy how to get started with socket.io with express 3. It is even ready to be push on dotCloud if you whish to share your app.