logo
down
shadow

I cannot emit any messages with socket.io


I cannot emit any messages with socket.io

By : Subair Kundukadavu
Date : November 21 2020, 11:01 PM
will be helpful for those in need I am trying to build a chat room, where I pass user session from passport + express to socket.io. but now I cannot emit any messages. io.on does not seem to connect. , This was my fix
code :
var express = require('express');
var app = express();
var server = require('http').Server(app);

var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

// Add connect-mongo to project - npm install connect-mongo
var MongoStore = require('connect-mongo')(session);

var configDB = require('./config/database.js');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var chatdb = require('./app/models/chat.js');

// configuration ===============================================================
// NOTE: This might need to be put into a callback/promise inside an initialize function
var db = mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating
var mongoStore = new MongoStore({
  mongooseConnection: db.connection,
});
app.use(session({
  secret: 'secret',
  clear_interval: 900,
  cookie: { maxAge: 2 * 60 * 60 * 1000 },
  store: mongoStore,
}));



// required for passport
app.use(session({ secret: 'secret' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/public'));




// Intercept Socket.io's handshake request
io.use(function(socket, next) {

    // Use the 'cookie-parser' module to parse the request cookies
    cookieParser('secret')(socket.request, {}, function(err) {

        // Get the session id from the request cookies
        var sessionId = socket.request.signedCookies ? socket.request.signedCookies['connect.sid'] : undefined;

        if (!sessionId) return next(new Error('sessionId was not found in socket.request'), false);

        // Use the mongoStorage instance to get the Express session information
        mongoStore.get(sessionId, function(err, session) {
            console.log('efe');
            if (err) return next(err, false);
            if (!session) return next(new Error('session was not found for ' + sessionId), false);

            // Set the Socket.io session information
            socket.request.session = session;
            console.log(sessionId);
            console.log(socket.request.user);

            // Use Passport to populate the user details
            passport.initialize()(socket.request, {}, function() {
                passport.session()(socket.request, {}, function() {
                    // This will prohibit non-authenticated users from connecting to your
                    // SocketIO server.
                    if (socket.request.user) {
                        next(null, true);
                    } else {
                        next(new Error('User is not authenticated'), false);
                    }
                });
            });
        });
    });
  });

// socket.io
io.on('connection', function(socket) {
    console.log('a user connected');

    socket.on('chat message', function(msg) {
        console.log('a use connected');
        var name = "efe";
        chatdb.saveMsg({
            name: name,
            msg: msg
        }, function(err) {
            if (err) throw err;
            io.emit('chat message', msg);
        });
    });

    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
});

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
http.listen(port);
console.log('The magic happens on port ' + port);


Share : facebook icon twitter icon
Reasons socket.io emit not receiving messages?

Reasons socket.io emit not receiving messages?


By : nanfeng
Date : March 29 2020, 07:55 AM
Hope that helps everyone for the comments, I believe I found the main issues. There were two things I think causing problems:
1) The bigger issue I think is that I'm use node clusters, and as a result users might join rooms on different workers and not be able to communicate with each other. I've ended up adding sticky sessions and Redis per the instructions here: http://socket.io/docs/using-multiple-nodes/
socket.emit not passing messages

socket.emit not passing messages


By : mats
Date : March 29 2020, 07:55 AM
should help you out Why do you say that you didn't get any errors in console? I got an error. I'll paste a screenshot of this:
code :
var socket = io.connect('http://localhost:3000', { path :'/' +home});
var socket = io.connect('http://localhost:3000');
How to consume the Socket IO to(-).emit(-) messages from client (Javascript)

How to consume the Socket IO to(-).emit(-) messages from client (Javascript)


By : Zedan
Date : March 29 2020, 07:55 AM
around this issue In my Node JS code, the SocketIO emits will be done with room ID. Out of all room connections to Socket IO, a corresponding room will consume the particular message. Currently, I am testing this application from my local by writing a JavaScript code but I am not sure how to consume this (No issues while just using emit as I can use socket.on()). Can someone help me with this? , On the client side use
code :
socket.on("message",function(data)
{
//do something
})
Emit/Broadcast Messages on REST Call in Python With Flask and Socket.IO

Emit/Broadcast Messages on REST Call in Python With Flask and Socket.IO


By : Soumo Pramanik
Date : March 29 2020, 07:55 AM
may help you . I just use Flask-SocketIO for that.
Using Socket IO to emit messages when a Node JS process is completed

Using Socket IO to emit messages when a Node JS process is completed


By : Nikhil
Date : March 29 2020, 07:55 AM
With these it helps if you want catch client.emit('messages', 'Hello from server'); you can simply do this
Related Posts Related Posts :
  • Unable to install nodemon node.js
  • How to POST items to an Azure SQL Easy Table from Node.js
  • Use of $nin on embedded document
  • What makes my node app restart every 30 seconds using pm2
  • Getting error while Installing Cordova plugin
  • Chrome 54 doesn't get HTTPS response from my site; Chrome 53, Chromium, Firefox, and Safari do
  • Raspberry Pi 3 script RAM usage
  • Received data from HTTP client is lost while sending it to a TCP server
  • harpjs not compiling stylus with harp server
  • node-postgres vs pg-promise for Nodejs Application
  • Deploy React Starter Kit (by Kriasoft) to Heroku
  • Heroku runs fine local but not online
  • What is the difference between the following two blocks of code?
  • NPM refusing to install Semantic-UI
  • Ionic 2 Build TypeError: Cannot read property 'AssetUrl' of undefined
  • Entity key and data properties not defined when retrieving from local datastore
  • I keep getting Connot GET /auth/twitter/callback in my callbackURL when using passport. What am I doing wrong?
  • How to refer to another collection in MongoDB
  • Handle 404 error with Express 4
  • heroku git dependency propagation
  • moongose: reading data from mongodb with nodejs
  • Order by in nested eager loading in sequelize not working
  • Amazon SQS doesn't supply my worker instance with the full message
  • control flow of callbacks with db returns in node js
  • Deleting uploaded files in Node.js with MongoDB
  • AWS Lambda function to updload json to s3 bucket not working
  • Can't reach webside with pm2
  • Timeout when sending email using nodemailer behind a corporate proxy
  • Trouble adding item with PUT to dynamodb table: node.js aws-sdk
  • Mongoose - Search dates stored as strings by date range
  • Cookie not set (undefined) node js
  • How to pass JSON object from API to server
  • Configure sphinx to rank exact matching higher with morphology enabled
  • Can’t gracefully shut down a node + Express app (node http server's close function does not complete)
  • Executing local (--save-dev) tools by npm
  • gulp clean is not working in correct manner
  • Conditional Writes DynamoDB: Expected params.ExpressionAttributeValues[':p'] to be a structure
  • How to use ES6 and ES7 in my Gruntfile
  • How to include the 'many' part of a relation from the 'one of many' model?
  • Build webpack on travis ci
  • How to insert data to mongo synchronously (Nodejs, Express)
  • Round Image corners GM ImageMagic, pass options
  • Executing Jobs as other user
  • On node how to you perform an insert if doesn't exists
  • Node version error while deploying Angular2 app on Azure
  • Node async.js: callback is not a function error?
  • How do i get the redis store client from socket-io-redis?
  • Issues trying to run electron based application?
  • AWS Lambda function write to S3
  • Passport-jwt token expiration
  • Sails, Sockets, and Authorization
  • What's the difference when using gulp and opening index.html directly in this case?
  • Server with Nodejs and client with XMLHttpRequest
  • Sails JS file upload; how to check if file is an input?
  • Trouble using passport-azure-ad OIDCStrategy with Passportjs
  • How to use else statement in jade template?
  • NPM install always fails to fetch NPM registry in Docker container at random times
  • Chai expect assertion to.have.string failure: UnhandledPromiseRejectionWarning
  • Node.js & Redis & For Loop with bluebird Promises?
  • Loopback "params" for running native SQL queries
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com