我有这个用Socket.io 1.2编写的代码
var app=require('express')();
var http=require('http').Server(app);
var io=require('socket.io')(http);
var room;
var messageEmitted;;
app.get('/', function(req, res){
res.sendFile(__dirname +'/index.html');
});
app.get('/lol', function(req, res){
res.sendFile(__dirname +'/lol.html');
});
io.use(function(socket,next){
var handShakeData=socket.request;
room=handShakeData._query['roomName'];
messageEmitted=handShakeData._query['messageText'];
next();
});
io.on('connection',function(socket){
console.log('A user connnected on : '+room);
socket.join(room);
io.to(room).emit('emittedMessages',messageEmitted);
console.log(messageEmitted);
/*socket.on('emittedMessages',function(msg){
//socket.emit(msg); // Send message to sender
socket.broadcast.emit(msg); // Send message to everyone BUT sender
});*/
socket.on('disconnect', function(){
// io.to(room).emit('emittedMessages','A User Disconnected on: '+room);
console.log('A user disconnected');
});
});
http.listen(3000,function(){
console.log('Listening oon Port: 3000');
});
这段代码非常合适。
我正在尝试从名为Gottox的android库中访问此代码,此版本需要0.9.16
但是,当我尝试通过输入以下命令移动到旧库(即0.9.16)时:
npm remove socket.io
npm install socket.io@0.9.16
当我跑步时:
node server.js
我收到此错误:
D:\NodeJSSocketBroadcast>node server.js
D:\NodeJSSocketBroadcast\server.js:3
var io=require('socket.io')(http);
^
TypeError: object is not a function
at Object.<anonymous> (D:\NodeJSSocketBroadcast\server.js:3:28)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
如何在旧版本的socket.io中实现相同的功能?我找不到任何文件。我还发现this link描述了相同的内容。
请帮忙。 :( :(
答案 0 :(得分:0)
const server = require('http').createServer();
var io = require('socket.io').listen(server);
server.listen(1337);`
但我建议使用https://github.com/nkzawa/socket.io-client.java - java实现支持socket.io 1.2.1