对socket.io有问题的节点的新手,试图将两个不同的aps连接到同一个socket.io服务器并且具有:
webindex.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
io.on('connection', function(client) {
client.on('color', function() {
console.log("color server");
client.emit('calor');
});
});
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index_web.ejs');
});
mobileindex.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
var db;
server.listen(3000);
app.set('view engine', 'ejs')
MongoClient.connect('mongodb://charlie:12345678@ds023674.mlab.com:23674/shapes', function(err,database){
if(err) return console.log(err);
db = database;
});
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
db.collection('shapes').find().toArray(function(err, result){
if (err) return console.log(err)
res.render('index.ejs', {shapes: result})
})});
app.get('/shapes/:id', function(req,res){
db.collection('shapes').find({"_id": ObjectId(req.params.id)}).toArray(function(err,result){
res.send(JSON.stringify(result[0]));
});
});
index.js
var socket = io.connect('http://localhost:8080');
socket.on('color', function(){
console.log('color');
sortShapes('color');
});
socket.on('shape', function(){
console.log('shape');
sortShapes("name");
});
function sortShapes(by){
var myArray = $("img");
console.log(myArray);
myArray.sort(function (a, b) {
a = $(a).attr(by);
b = $(b).attr(by);
if(a > b) {
return 1;
} else if(a < b) {
return -1;
} else {
return 0;
}
});
$("#original").append(myArray);
}
$(function() {
$("img").mouseover(function(){
$.ajax({
type: "GET",
url: "http://localhost:3000/shapes/" + $(this).attr("mongo_id"),
success: displayShapeInfo,
error: function(){
console.log("Error!")
},
dataType:"json"
});
});
function displayShapeInfo(shape){
$('#shape_info').text("type: " + shape.name + " color: " + shape.color + " times seen: " + shape.times_seen);
addTimesSeen(shape._id);
}
function addTimesSeen(id){
$.ajax({
type: "PUT",
url: "http://localhost:3000/shapes/" + id,
});
}
});
index_web.js
var socket = io.connec('http://localhost:8080');
$(function(){
$('#color').on('click', function(){
console.log("color");
socket.emit('color');
})
$('#shape').on('click', function(){
console.log("shapes");
socket.emit('shape');
})
});
为什么index.js中的socket.on无法正常工作?
我确定事件被正确触发。