WebSocket是html5新增加的一种通信协议,目前流行的浏览器都支持这个协议,例如 Chrome,Safrie,Firefox,Opera,IE等等,对该协议支持最早的应该是chrome,从chrome12就已经开始支持,现在浏览器基本都支持 CanIUse
1. 先写一个简单的demo
先祭出文档, 木的中文的
server
const Koa = require('koa')
let app = new Koa
const server = require('http').createServer(app.callback())
const io = require('socket.io')(server)
const fs = require('fs')
app.use(( ctx) => {
ctx.type = 'html'
ctx.body = fs.createReadStream('./test.html')
})
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log(msg)
});
setTimeout(() => {
socket.emit('zpzpzpzpzp', "this is test message")
}, 5000)
});
server.listen(3001, () => {
console.log(`listenning at 3001`)
})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Hello World</h1>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<script>
var io = io()
setTimeout(function() {
io.emit('chat message', 'zzzzz')
}, 3000)
io.on('zpzpzpzpzp', function(msg) {
let p = document.createElement('h1')
p.innerText = msg
document.querySelector('body').appendChild(p)
})
</script>
</body>
</html>
3s 后 服务端收到来自客户端的信息,5s 后服务端发布信息,客户端打印到页面上
2. 如果指定某个id进行发送
io.sockets.connected[socket.id].emit('zpzpzpzpzp', "this is test message")
网友评论