node 简单实现socket 客户端与服务器通信

参考 http://www.open-open.com/lib/...

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




    
    Document


    

test

你可能感兴趣的:(socket.io,node.js)