npm install socket.io
感觉和vuex redux 差不多
chat_server.js
const express = require("express")
const app = express()
const http = require("http").Server(app)
const socket = require("socket.io")
const io = socket(http)
app.use( express.static("public") )
let onlineUser = {}
let onlineCount = 0
io.on("connection",function(socket){
socket.on("login",function(obj){
socket.name = obj.userid
if( !onlineUser.hasOwnProperty(obj.userid) ){
onlineUser[obj.userid] = obj.username
onlineCount++
}
io.emit("login",{
onlineUser:onlineUser,
onlineCount:onlineCount,
user:obj
})
console.log( obj.username + '加入了聊天室' )
console.log("在线人数: " + onlineCount )
})
})
http.listen(80,function(){
console.log(80)
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>test</p>
<script src="https://cdn.bootcss.com/socket.io/1.7.3/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.emit("login",{userid:Date.now(),username:'taoqun'},function(data){
console.log(data)
})
socket.on("login",function(data){
console.log(data)
})
</script>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。