我正在创建简单的socket io应用程序,也遵循web上的所有教程,通过Node JS实现socket-io。当前代码仅工作一次,并且在连接套接字后自动断开连接。从那之后,我尝试了所有PnC,但它没有连接服务器端。
任何人都可以帮助我确定我做了什么愚蠢行为吗?此外,我不理解它是客户端问题还是库问题。
{
"name": "IntellicarMaps",
"version": "1.0.0",
"description": "Demo app showing the use of Google Maps for Intellicar",
"main": "server.js",
"author": "Prateek",
"dependencies" : {
"express" : "~4.7.2",
"mongoose" : "~4.1.0",
"morgan" : "~1.2.2",
"body-parser": "~1.5.2",
"jsonwebtoken": "^5.0.2",
"method-override": "~2.1.2",
"socket.io": "~1.4.8"
}
}
// Dependencies
// -----------------------------------------------------
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 3000;
var database = require('./app/config');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
var server = require('http').createServer(app);
global.io = require('socket.io').listen(server);
//------------------
// Express Configuration
// -----------------------------------------------------
// Sets the connection to MongoDB
mongoose.connect(database.localtest.url);
// Logging and Parsing
app.use(express.static(__dirname + '/public')); // sets the static files location to public
app.use('/bower_components', express.static(__dirname + '/bower_components')); // Use BowerComponents
app.use(morgan('dev')); // log with Morgan
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.urlencoded({extended: true})); // parse application/x-www-form-urlencoded
app.use(bodyParser.text()); // allows bodyParser to look at raw text
app.use(bodyParser.json({ type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride());
//----------
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// Routes
// ------------------------------------------------------
require('./app/routes.js')(app);
// Listen
// -------------------------------------------------------
//app.listen(port);
server.listen(port);
console.log('App listening on port ' + port);
//------------------------
// Socket io connection
//------------------------
io.on('connection', function(socket){
console.log('a user connected'); //this is not printing in console.
socket.emit('my other event', { my: 'data' });
//socket.on('disconnect', function(){
//console.log('user disconnected');
//});
});
io.emit('message',{"AlarmName":"CPU_FAN_DOWN"});
<script src="../lib/socket.io.js"></script>
<script>
var socket = io('http://localhost', {'force new connection': true});
socket.on('message', function (data) {
console.log(data);
});
</script>
此文件始终已加载,我已在浏览器控制台中进行了检查