node-express给客户端发送消息
服务端:
第一种写法:
const app = require('express')();
var server = require('http').Server(app)
var io = require('socket.io')(server);
server.listen(8080);
// io.on('connection',function(socket){
// socket.emit('news',{hello:'hello'})
// })
var chat = io.of('/lisdfn').on('connection',function(socket){
chat.emit('chat','chatmsg');
})
var news =io.of('/news').on('connection',function(socket){
news.emit('news','newsmgs')
})
第二种写法:
注意:端口不能相同
var app = require('express')();
app.listen(8889);
var io = require('socket.io')(8888)
var chat = io.of('chat').on('connection',function(ss){
chat.emit('chat3','hello chat3 !')
})
客户端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
<script>
var news = io.connect('http://localhost:8080/news');
var chat = io.connect('http://localhost:8080/lisdfn');
news.on('news',function(data){
console.log(data)
})
chat.on('chat',function(data){
console.log(5,data)
})
</script>
</body>
</html>