My problem is that socket.emit is taking so much time to send the data to the server, i have tried anything but i got no results, this is the code:
Client side
$( "#mensaje" ).keypress(function( event ) {
if ( event.which == 13 ) {
$('.botonEnviarMensaje').click();
}
});
$('.botonEnviarMensaje').click(function(){
var myInput = document.getElementById("mensaje");
if(!isEmpty(myInput.value)){
socket.emit('newMessage',dataPerson,myInput.value)
console.log("envie un mensaje")
}
$('#mensaje').val('');
})
Server side
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 3000;
const app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const util = require('util')
app.use('/',express.static(path.resolve(__dirname, '../../public')));
app.get('/',(req,res)=>{
res.sendFile(path.resolve(__dirname + '/../../public/Login/index.html'))
})
io.on('connection', function(socket){
console.log('a user connected');
socket.on('newMessage',function(data,value){
console.log("llego un mensaje")
io.sockets.emit('messageAll',data,value);
})
});
Related
Hi I am trying to setup a connection with socket.IO but not able to do so. At present I am not getting any error but the connection is not taking place.Please find below the relevant details :
app.js
const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
const http = require('http').createServer(app);
var io = require('socket.io');
socket = io(http, {cors: {
origin: "http://localhost",
methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors());
const portCheck = process.env.PORT || 3001
socket.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('greeting-from-server', {
greeting: 'Hello Client'
});
});
app.listen(portCheck, ()=> {
console.log('Server Listening to port:' + portCheck);
})
Changes should done for your code as follows:
Change app listen with server listen
wrap socket.on(//...) with io.on(//...)
replace this lines
const app = express();const http =
require('http').createServer(app);
with
var server = require('http').Server(app);
var io = require('socket.io')(server);
After the changes code is like follows.
const express = require('express');
require('./db/mongoose');
const functions = require("firebase-functions");
var bodyParser = require('body-parser');
const app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
socket = io(http, {cors: {
origin: "http://localhost",
methods: ["GET", "POST"]
}
});
var cors = require("cors");
var cookieParser = require('cookie-parser');
var path = require('path');
app.use(cors());
const portCheck = process.env.PORT || 3001
server.listen(portCheck, ()=> {
console.log('Server Listening to port:' + portCheck);
})
io.on('connection', (socket)=> {
socket.on('connection', function (socket) {
console.log('connected to socket');
socket.emit('greeting-from-server', {
greeting: 'Hello Client'
});
});
});
follow more information through this link. https://socket.io/get-started/chat.
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
I have an Express server which works well, but now I want to set up Socket.io in it,
I have the error TypeError: require(...).listen is not a function
My current code (working well)
const app = express();
app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), () => {
console.log("Server running");
});
Code trying to set up Socket.io
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Server running");
});
const io = require("socket.io").listen(server);
Can someone help me with the error above please ?
From the SocketIO documentation, to setup SocketIO with the express application, it should be:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});
I have deployed an app with Heroku. I have a chat. It work fine in local but not with the online app.
index.js in my server :
const express = require('express');
const bodyparser = require('body-parser');
const security = require('./middleware/security');
const userRouter = require('./routes/user');
const AnnonceRouter = require('./routes/annonce');
const securityRouter = require('./routes/security');
const commentRouter = require('./routes/comment');
const mailRouter = require('./routes/mail')
const path = require('path');
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
const app = express();
const cors = require('cors');
var chat = require('https').createServer(app)
var io = module.exports.io = require('socket.io')(chat)
const SocketManager = require('./SocketManager')
io.on('connection', SocketManager)
if (process.env.NODE_ENV === 'production') {
app.use(express.static('../client/build')); // serve the static react app
app.use(cors());
app.use(bodyparser.json());
app.use(security.verifyToken);
app.use('/annonce', AnnonceRouter);
app.use('/user', userRouter);
app.use('/comment', commentRouter);
app.use('/mail', mailRouter);
app.get(/^\/(?!api).*/, (req, res) => { // don't serve api routes to react app
res.sendFile(path.join(__dirname, '../client/build/index.html'));
})
app.use('/', securityRouter);;
console.log('Serving React App...');
};
app.listen(PORT, function () {
console.error(`Node ${isDev ? 'dev server' : 'cluster worker '+process.pid}: listening on port ${PORT}`);
});
the file when i use it
const socketUrl = "https://teachonline.herokuapp.com"
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
socket:null,
user:null
};
}
componentWillMount() {
this.initSocket()
}
/*
* Connect to and initializes the socket.
*/
initSocket = ()=>{
const socket = io(socketUrl)
socket.on('connect', ()=>{
console.log("Connected");
})
this.setState({socket})
}
I tried something different, but the result is still the same.
My request looks like that : https://teachonline.herokuapp.com/socket.io/?EIO=3&transport=polling&t=MpFHcqj
But i get a code 401 "Unauthorized"
If you have an idea of what am i doing wrong, i'm listening.
Instead of PORT_CHAT, use PORT.
const isDev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 5000;
const PORT_CHAT = 3231;
const app = express();
const cors = require('cors');
var chat = require('https').createServer()
var io = module.exports.io = require('socket.io')(chat)
const SocketManager = require('./SocketManager')
io.on('connection', SocketManager)
chat.listen(PORT, ()=>{
console.log("Connected to port:" + PORT);
})
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;