2017-07-31 74 views
0

我有一個node.js服務器在heroku端這是在本地主機上工作,但是當我承諾heroku的應用程序崩潰。heroku節點js + socket.io listion從php

'use strict'; 

const express = require('express'); 
const socketIO = require('socket.io'); 
const path = require('path'); 

const PORT = process.env.PORT || 3000; 
const INDEX = path.join(__dirname, 'index.html'); 

const server = express() 
    .use((req, res) => res.sendFile(INDEX)) 
    .listen(PORT,() => console.log(`Listening on ${ PORT }`)); 

const io = socketIO(server); 

io.on('connection', (socket) => { 
    console.log('Client connected'); 
    socket.on('disconnect',() => console.log('Client disconnected')); 
}); 


var app = express(); 
app.set('port', (process.env.PORT || 5000)); 

var bodyParser = require('body-parser') 
app.use(bodyParser.json()); 

app.use(express.static(__dirname + '/public')) 

app.post('/phpcallback', function(req, res) { 
    var content = req.body; 
    console.log('message received from php: ' + content.msg); 
    //to-do: forward the message to the connected nodes. 
    res.end(content.msg); 
}); 

app.listen(app.get('port'), function() { 
    console.log("Node app is running at localhost:" + app.get('port')) 
}); 

應用程序需要監聽POST requet而來形成我的PHP服務器,然後發射到用戶在JS客戶端,代碼工作良好,當其對loclhost但是當我提交和推到Heroku的應用程序崩潰。 任何人都知道什麼是問題?我是新來的Node.js和socket.io

回答

0

嘗試這樣的(改善語法和一般使用)

var express = require('express'); 
var io = require('socket.io'); 
var path = require('path'); 
var PORT = process.env.PORT || 3000; 
var INDEX = path.join(__dirname, 'index.html'); 
// Express & Middleware 
var app = express(); 
var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 
// SocketIO 
var server = require('http').createServer(app); 
var io = require('socket.io')(server); 
io.on('connection', function(){ 
    console.log('[socket]','client connected'); 
    socket.on('disconnect',() => console.log('[socket]','client disconnected')); 
}); 
server.listen(PORT,function(){console.log("[SERVER] listening @ port:",PORT);}); 
//GET Routes 
app.use(express.static(__dirname + '/public')) 
app.get('/',function(req,res){res.sendFile(INDEX);}); 
//POST Routes 
app.post('/phpcallback', function(req, res) { 
    var content = req.body; 
    if(content.msg){ 
    console.log('message received from php: ' + content.msg); // 
    /*to-do: forward the message to the connected nodes.*/ 
    //io.sockets.on('forward',content.msg); //forward to ALL connected socket.io clients (requires client-side event) 
    res.send(content.msg); //forward response with content.msg to the original request (only) of this route. 
    }else{console.log('[/phpcallback] : missing message (content.msg)');} 
}); 

我看到了你的to-do,如果你想將消息轉發給所有連接的客戶端接口。 IO:

io.sockets.emit('your_event','your_message'); 

這可能來方便:SocketIO Emit CheatSheet