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

Taoqun

参考 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

<!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>
阅读 3.9k

[链接]

131 声望
5 粉丝
0 条评论

[链接]

131 声望
5 粉丝
文章目录
宣传栏