I'm currently developing an application to stream video feed from client to server in NodeJS. The server side code is as shown below
server.js
const express = require('express')
const app = express()
const morgan = require('morgan')
const server = require('http').Server(app)
const io = require('socket.io')(server)
const auth = require('./routes/auth')
const video = require('./routes/videoproc')(io)
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(morgan('dev'))
app.use("/users", auth)
app.use("/exam", video);
server.listen(3000)
videoproc.js
const express = require('express')
const video = express.Router()
const ss = require('socket.io-stream')
const fs = require('fs')
const path = require('path')
module.exports = (io) => {
video.post('/video', (req, res) => {
io.on('connection', (socket) => {
ss(socket).on('video', (stream, data) => {
const fileName = path.basename('test')
stream.pipe(fs.createWriteStream(fileName))
})
})
})
return video
}
This is the client side code
var io = require('socket.io-client');
var ss = require('socket.io-stream');
var fs = require('fs')
var socket = io.connect('http://localhost:3000/exam/video/');
var stream = ss.createStream();
var filename = './test.webm';
ss(socket).emit('video', stream, {name: filename});
fs.createReadStream(filename).pipe(stream);
As a test I've send a video feed to the server but the file is not being stored, some help to solve this issue is appreciated.
Server you should:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(morgan('dev'))
// app.use("/users", auth)
app.use("/exam", video);
io.on('connection', (socket) => {
console.log('CONNECTED');
ss(socket).on('video', (stream, data) => {
console.log('RECEIVED');
const fileName = path.basename('test')
stream.pipe(fs.createWriteStream(fileName))
})
})
server.listen(3000)
and Client: param in a connect function is just "http://localhost:3000/", exclude route
var socket = io.connect('http://localhost:3000/');
var stream = ss.createStream();
var filename = './test.webm';
ss(socket).emit('video', stream, {name: filename});
fs.createReadStream(filename).pipe(stream);
At client: connect to a domain, not route:
ref
At server: you placed io.on on a route, io.on is just listen when you call the route. if you want run when server starting, you should place io.on outside the route
Related
I Have code like this.
const pino = require('pino')
const { Boom } = require('#hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
require('dotenv/config')
const express = require('express')
const socket = require("socket.io");
const { toDataURL } = require('qrcode')
const mysql = require('mysql');
require('dotenv').config();
const request = require('request');
const { smsg } = require('./app_node/lib/myf')
const app = express()
const host = process.env.HOST
const port = parseInt(process.env.PORT)
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
const ser = app.listen(port, host, () => {
console.log(`Server is listening on http://${host}:${port}`)
})
const io = socket(ser);
how do i get my code to run on the https server
i want to run my server in https in nodejs
I'm having trouble understanding how web sockets work. I'm not seeing my console.log "connection" inside the io.on function when I visit http://www.localhost:3010 in my browser. Could someone explain why that is?
server.js:
const app = require("./backend/app")
const http = require('http');
const server = http.createServer(app)
var socketIo = require('socket.io')
server.listen(3010, () => {
console.log("listening")
})
const io = socketIo(server)
io.on("connection", (socket) => {
console.log("connection")
socket.emit("news", {hello: "world"})
})
app.js:
const express = require("express");
const app = express();
app.get("/", (req, res, next) => {
res.send("hello world");
})
module.exports = app
I need to break a timer on a socket event and my Nodejs Express Socket.io App looks like this:
app.js
const express = require('express') ;
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const api = require('./routes/api');
const users = io.of('/users') ;
const usersNamespace= (socket) => {
socket.on('disconnect',()=>{
});
}
users.on('connection',usersNamespace) ;
app.use('/api', api);
// make socket.io accessible in the express router
app.use((req,res,next)=>{
req.io = io;
req.users = users;
next();
});
server.listen('8000');
my ./routes/api.js file looks like:
var express = require('express');
var router = express.Router();
router.post('/test',req,res) {
// broadcast body of request to users namespace
req.users.emit('restreq',req.body) ;
var timer = setInterval(()=>{
console.log('hello');
}, 5000);
res.status(200).json('received') ;
}
module.exports = router;
The question is how i can do clearInterval and stop the timer on a receiving socket event?
You can pass a function or object to deal with intervals as you do with users:
app.js
const express = require('express') ;
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const api = require('./routes/api');
const users = io.of('/drivers') ;
const timer = {
hInterval: null,
register: hInterval => {
timer.hInterval = hInterval
},
disable: () => {
clearInterval(timer.hInterval)
timer.hInterval = null
}
}
const usersNamespace = socket => {
socket.on('disconnect', () => {
timer.disable()
});
}
users.on('connection', usersNamespace) ;
app.use('/api', api);
// make socket.io accessible in the express router
app.use((req, res, next)=>{
req.io = io;
req.users = users;
req.timer = timer;
next();
});
server.listen('8000');
api.js:
var express = require('express');
var router = express.Router();
router.post('/test', req,res) {
// broadcast body of request to users namespace
req.users.emit('restreq',req.body) ;
req.timer.register(setInterval(() => {
console.log('hello');
}, 5000));
res.status(200).json('received') ;
}
module.exports = router;
I'm trying to use socket Io in my server and when I try to acessas the service was I create the browser its given this error:
ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Here is my server code:
'use strict';
const chalk = require('chalk');
const _ = require('lodash');
const fs = require('fs');
let options = {
key: fs.readFileSync("privkey.pem"),
cert: fs.readFileSync("cert.pem")
};
const app = require('express')(options);
const https = require('https').Server(app);
const io = require('socket.io')(https,{origins:'*:*'});
const bodyParser = require('body-parser');
const multer = require('multer'); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
const sockets = {};
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
https.listen(3002, function () {
console.log(chalk.yellow("Serviço rodando na porta 3002"));
});
io.on('connection', function (socket) {
console.log(chalk.green("Cliente Conectado"));
sockets[socket.id] = socket;
socket.on('disconnect', function () {
console.log(chalk.red("Cliente Disconectado"));
delete sockets[socket.id];
});
});
app.post('/atualizador', upload.array(), function (req, res) {
_.each(sockets,function(socket,idSocket){
console.log(idSocket);
socket.emit('posicao',req.body);
});
res.send('Atualizador ON');
});
And here is the client code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
const socket = io('https://localhost:3002/');
socket.on('posicao', function(msg){
console.log(msg);
});
</script>
This certs and privatekey already is used on my domain and why is not working on socket.io and express?
You should pass nothing to express and options and app to https.Server:
const app = require('express')();
const https = require('https').Server(options, app);
I would like to use socket.io and express routes and I have the following code:
app.js
var
http = require('http'),
path = require('path'),
passport = require('passport'),
userpassport = require('./lib/strategies/local'),
githubpassport = require('./lib/strategies/github'),
flash = require('connect-flash'),
express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
errorhandler = require('errorhandler'),
csrf = require('csurf'),
favicon = require('serve-favicon'),
sockets = require('./lib/socket'),
app = express();
var routes = require('./routes')();
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function () {
var io = require('socket.io')(server);
io.on('connection', function (iosocket) {
sockets.setSocket(iosocket);
});
});
lib/socket.js
var socket;
exports.setSocket = function(iosocket) {
console.log('setting socket');
socket = iosocket;
}
exports.getSocket = function() {
console.log('getting socket');
return socket;
}
routes/index.js
var sockets = require('../lib/socket');
module.exports = function () {
var routes = {};
routes.index = function (req, res) {
var socket = sockets.getSocket();
socket.on('app/create', function (data) {
console.log('got app create');
});
}
This does not work, I think it's because the setSocket function that appears on app.js runs after the page was loaded, therefore when I getSocket on the route it's not the latest socket (I can console log the given socket on the route, I can see there's a socket there, but I can also see that the setSocket runs afterwards).
How can I solve this?