socket的简单使用
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="https://cdn.socket.io/3.1.1/socket.io.min.js"></script>
</head>
<body>
<input type="text" id="input"><button id="btn">send</button>
<ul id="ret"></ul>
<script>
var input = document.querySelector('#input')
var btn = document.querySelector('#btn')
var ret = document.querySelector('#ret')
var socket = io()
btn.addEventListener('click', function () {
socket.emit('chat', input.value)
input.value = ''
})
socket.on('chat', function (msg) {
var item = document.createElement('li');
item.textContent = msg;
ret.appendChild(item);
})
</script>
</body>
</html>
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
socket.on('chat', function (msg) {
io.emit('chat', 'server:' + msg)
})
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
前后端通过emit、on完成数据的通信,需要实时数据的前端只需要订阅对应的事件,就可以拿到实时的数据
胖胖熊笔记,笔记已迁移