socket.io
为什么使用socket.io 1. 简单 2. 高效:连接池的管理比自己写的要高效(通常)
客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="node_modules/socket.io/client-dist/socket.io.js"></script>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="发送" onclick="send()">
<script>
var socket = io.connect('http://127.0.0.1:3000')
function send() {
var text = document.getElementById('text').value
// 随机时间绑定 和服务端的写的一样
.emit('sendMsg',text)
socket
}</script>
</body>
</html>
服务端
const { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"]
};
})
.on("connection", (socket) => {
io.on('sendMsg',(data)=>{
socketconsole.log(data)
});
})
.listen(3000,function (){
httpServerconsole.log('http://127.0.0.1:3000')
; })