I'm testing socket.io and do a simple chat message (following the tutorial in the official website)
I opened 2 windows:
When I emit the event in the first window opened, its ok.
But, when I emit the event in second window this send the event 2 times(duplicated).
PS: if I open a third window, this send the event 3 times
Node.js code:
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
io.on('connection', function(socket) {
socket.on('chatMessage', function(msg){
io.emit('chatMessage', msg);
});
});
});
Client side:
methods: {
sendMessage: function () {
socket.emit('chatMessage', this.text);
}
socket.on('chatMessage', function(msg){
console.log('Client side message: ' + msg)
vmIndex.messages.push(msg);
});
It's because you're creating a connection listener every time someone visits the '/' route. Try moving the socket-io code outside of the '/' route function.
As Eric mentioned, move your connection listener outside of the / route in order to prevent it from getting created every time someone visits the page.
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
io.on('connection', function(socket) {
socket.on('chatMessage', function(msg){
io.emit('chatMessage', msg);
});
});
Related
I have created a socket.io chat application on my virtual server (Ubuntu), which runs as an systemd service and which is active running.
My server.js is located in:
/var/www/vhosts/mywebpage.de/w1.mywebpage.de/chat/
The server.js looks like this:
const io = require('socket.io')(3055);
io.on('connection', function(socket) {
// When the client emits 'addUser', this listens and executes
socket.on('addUser', function(username, room) {
...
});
// When the client emits 'sendMessage', this listens and executes
socket.on('sendMessage', function(msg) {
...
});
// Disconnect the user
socket.on('disconnectUser', function(username, room) {
...
});
});
In my website (https) I try to connect as follow:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script type="text/javascript">
var loSocket;
$(document).ready(function() {
if(typeof(loSocket) == 'undefined') {
loSocket = io('https://w1.mywebpage.de:3055', {
reconnectionAttempts: 5,
forceNew: true
});
}
});
</script>
But I can't get a valid connection.
The developer tools say this:
(failed) ERR_CONNECTION_CLOSED with initiator polling-xhr.js:264.
What could be the error ?
From what I have done in the past I would create a https server which serves the SSL cert and create the socket server using the https server you created, this will allow you to connect via https and you will need to enable secure on socketio (use this question as a ref)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var 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.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Use this code as ref on how to create a socketio server using http
You can find this code on the socket.io docs
NOTE: You will need to you https not http like shown in the example
I want to send messages from the server to the client and implement this in routes/index.js of my mean stack project. Does anyone know how to use socket.io here?:
router.post('/message/sendMessage', function (req, res, next) {
console.log("router.post /message/sendMessage " + req.body)
// send req.body to client
});
PS: Previously, I have used socket.io one time in the project: the client opens a socket, and then the server emits a message named id, the client receives it. In the client:
socket = io.connect();
socket.on('id', function (id) { ... })
In www (server):
io.sockets.on('connection', function (socket) {
console.log("LOG: just connected: " + socket.id);
socket.emit('id', socket.id);
socket.on('disconnect', function () {
console.log("LOG: just disconnected: " + socket.id)
})
})
But I cannot imagine how to write socket.emit inside Expressjs routing...
Edit 1: I tried to do the following to send a message to all the clients but in the console, it only displayed until before emit, and in the client it showed Failed to load resource: the server responded with a status of 500 (Internal Server Error)
router.post('/message/sendMessage', function (req, res, next) {
console.log("router.post /message/sendMessage");
console.log("before emit");
io.sockets.on('connection', function (socket) {
console.log("LOG: just connected: " + socket.id);
io.emit("message", "this is a test");
socket.on('disconnect', function () {
console.log("LOG: just disconnected: " + socket.id)
})
})
console.log("after emit");
});
Actually my question comes down to a common question: how to use socket.io inside an express routes file.
And I have found a super answer: https://stackoverflow.com/a/31277123/702977
So in www:
var io = require('socket.io').listen(server);
app.set('socketio', io);
and in index.js:
router.post('/message/sendMessage', function (req, res, next) {
console.log("router.post /message/sendMessage");
var io = req.app.get('socketio');
io.emit("message", "hi!");
res.json("hahaha")
});
If I want to send a message to a certain client, I need to pass the information like id as a parameter into router.post, and then use for example io.to(req.body.id).emit("message", req.body.message);
Hi i am working with socket.io and node.js (express.js).
I saw a lot of examples, coding from the app.js file. Now i would like to organize better the code, i would like to have all my sockets.io handlers in other modules/files.
This is what i have now:
app.js
var moduleExports = require('./routes/moduleExports');
app.get('/', function(req, res){
res.sendfile(path.join(__dirname + '/index.html'));
io.on('connection', function(socket){
moduleExports.socketio(io, socket);
});
});
moduleExports.js
module.exports = {
init: function(){
//some other functions
}, socketio: function(io, socket){
socket.emit('chat', 'Wellcome!');
socket.on('chat', function (data) {
socket.broadcast.emit('chat', data);
//socket.broadcast.emit('chat', data);
});
socket.on('disconnect', function () {
socket.broadcast.emit('chat', 'Disconnected');
//socket.broadcast.emit('chat', data);
});
}
};
PROBLEM:
If I open 2 different browsers, one browser is for John and one browser is for Doe.
If John sends a message, Doe recieve it two times. If I open again a third browser, and send a message from John, Doe and the third browser are reciving three times the message.
I dont know exactly why this happen. I know something is happen with the "moduleExports.js" file. But I need a way to code my socket.io handlers outside of app.js. So i thought this would be a good pattern but it isnt.
By the way, the client code (it works):
<script src="/socket.io/socket.io.js"></script>
var socket = io();
function submit(){
socket.emit('chat', $('#m').val());
$('#m').val('');
return false;
}
The io.on('connection' you should have it just once in your code, everytime a client connects to your server that event will be thrown, if you have it multiple times I guess it runs more times. What I would do is the the following:
var moduleExports = require('./routes/moduleExports');
io.on('connection', function(socket){
moduleExports.socketio(io, socket);
});
app.get('/', function(req, res){
res.sendfile(path.join(__dirname + '/index.html'));
});
I have a function that runs on a click, I want this click to redirect to a other view. like a simple link.
how can I render a new view onclick?
node
router.post('/shareinsight', function(req, res, next) {
console.dir(req.body)
var db = req.db_login;
console.log('fs' + req.body.date)
res.redirect('contact');
});
I can see the log in the console so I know that the function is running but it doesn't change view
Try to use this code:
router.post('/shareinsight', function(req, res, next) {
console.dir(req.body)
var db = req.db_login;
console.log('fs' + req.body.date)
res.writeHead(302, {
'Location': 'url'
});
res.end();
});
I have an express node.js server serving Socket.io. I would like the ability to make get requests to the express server that will automatically send a message to a channel.
var app = require('express').createServer()
, io = require('socket.io').listen(app)
app.listen(80);
app.get('/:channel/:message', function (req, res) {
//Code to create socket
socket.emit("sent from get", {channel:req.params.channel, message:req.params.message})
});
io.sockets.on('connection', function (socket) {
socket.on('sent from get', function (data) {
socket.broadcast.to(data.channel).emit('channel message', { message: data.message});
});
});
How to I create (and destroy) a socket connection in the app.get block?
(For clarity, I want to use this to send a quick message from a rails server when a particular object is saved, and have a message pushed to each appropriate user.)
io.sockets.in(req.params.channel).emit("channel message", {mes:req.params.message})
That will send a message to all users in the requested channel.
var chat = io.of('/chat').on('connection', function (socket) {
socket.emit('a message', { that: 'only', '/chat': 'will get' });
chat.emit('a message', { everyone: 'in', '/chat': 'will get' }); });
The following example defines a socket that listens on '/chat'