直接使用Socket.io官网上面的demo,代码是直接复制的,所用到的express,socket.io都已经安装,可client端不能将消息广播到server端,不知道是什么原因?
server:
var app=require("http").createServer(handler);
var io=require("socket.io")(app);
var fs=require("fs");
app.listen(8000);
function handler(req,res){
fs.readFile('index.html',function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading index.html')
}
res.writeHead(200);
res.end(data);
});
}
// console.log('io',io);
io.on('connection',function(socket){
socket.emit('broadcast news',{hello:'world'});//广播消息
socket.on('listen client',function(data){
console.log("ccc",data);
console.log("client messages",data);
})//监听所有的客户端发来的消息
})
client:
<!DOCTYPE html>
<head>
<title>Socket.io</title>
</head>
<body>
<div>socket.io</duv>
<script src="/socket.io/socket.io.js" type="text/javascript"/>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>
1.在客户端连接中,如楼上所说,你的客户端连接端口没有设置,当然连接不到服务
2.你的服务端socket发送的事件是'broadcast news'监听的是'listen client'
而客户端监听的事件是'news'发送的是'my other event'...你告诉我该怎么监听好吧!
官网文档明明给出的代码是:
监听和发布都对不上...怎么会有处理?