Can I set up socket.io chat on heroku?

前端 未结 7 563
栀梦
栀梦 2021-02-01 16:46

I have a simple socket.io chat application which I\'ve uploaded to one of the new Heroku \'cedar\' stacks.

Now I almost have everything working but I\'ve hit one stumbli

相关标签:
7条回答
  • 2021-02-01 17:12

    I was able to get Socket.IO v0.8 to work on Heroku Cedar by doing the following:

    Within the Express app (in CoffeeScript in my case):

    app = express.createServer();
    socket = require("socket.io")
    
    ...
    
    io = socket.listen(app);
    io.configure () ->
      io.set("transports", ["xhr-polling"])
      io.set("polling duration", 10)
    
    io.sockets.on('connection', (socket) ->
      socket.on('myaction', (data) ->
        ...
        socket.emit('result', {myData: data})
    
    ### The port setting is needed by Heroku or your app won't start
    port = process.env.PORT || 3000;
    app.listen(port);
    


    And within the front-facing Javascript of your application:

    var socket = io.connect(window.location.hostname);
    function sendSocketRequest() {
      socket.emit('myaction', $("#some_field").val());
    }
    
    socket.on('result', function(data) {
      console.log(data);
    }
    

    Helpful links:

    • Heroku Node help
    • Heroku Socket.IO help
    0 讨论(0)
提交回复
热议问题