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
}
Related
my friend and I are both using the same wifi network with open ports for both of us. My friend is listening on port 8000 and I'd like to send him a message.
How can I achieve that using node and socket.io ? Thanks a lot
There are many ways to setup a simple messenger, the standard one is to setup a single socket.io server either on your or your friend's machine, something like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8000);
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.on('connection', function (socket) {
console.log("user connected!")
socket.on('message', function (message) {
//Sends message to all connected sockets
socket.broadcast.emit("message")
});
});
Then your index.html should have some code for connecting to server and sending messages:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://server-ip-or-domain-name:port');
socket.on('message', function (message) {
//processing incoming message here
console.log(message);
});
function sendMessage(msg){
//sends message to server
socket.emit("message", msg);
}
</script>
In this setup both you and your friend should be able to reach the server machine. Use pings for debuging.
p.s. havent tested the code above, but that's the idea.
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 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
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.