利用H5的webSocket写聊天室效果

首先要安装ws和express插件

{
  "dependencies": {
    "express": "^4.17.0",
    "ws": "^7.0.0"
  }
}

写聊天室结构





    
    
    
    WebSocket




    

聊天室


连接服务器js代码

/* 
  连接服务器

*/
const wsPort = 8010
const hostname = '10.31.163.80'
const ws = new WebSocket(`ws://${ hostname }:${ wsPort }`)

ws.onopen = () => {
    // 进入聊天室的提示
    ws.send('欢迎xxx来到xxx的直播间')
}

// 接收数据,然后将数据展示到界面上
ws.onmessage = (msg) => {
    const content = document.querySelector('#content')
    content.innerHTML += msg.data + '
' } // 异常报出 // ws.onerror = ( 'error' ) => { // console.log( error ) // } ws.onclose = () => { console.log('closed') }

客户端配置静态服务器

//给client启动一个静态服务器,用于展示页面
const express = require("express")
const path = require("path")
const webPort = 4000
const hostname = "10.31.163.80"
const app = express()
app.use(express.static(path.join(__dirname, "client")))
app.listen(webPort, hostname, () => {
    console.log(`The web server is running at:http://${hostname}:${webPort}`)
})

服务端配置服务器

//安装ws模块来创建服务器 
const WebSocket = require("ws");
const ws = new WebSocket.Server({ port: 8010, host: "10.31.163.80" });
let clients = {};
let clientName = 0;
ws.on("connection", (client) => {
    client.name = ++clientName
    clients[client.name] = client
    client.on("message", (msg) => {
        console.log(msg) //客户端接受到的信息
        Broadcast(client, msg)
    })
    client.on("close", () => {
        delete clients[client.name]
        console.log(client.name + "离开了~~~")
    })
})

function Broadcast(client, msg) {
    for (var key in clients) {
        clients[key].send(client.name + "说:" + msg)
    }
}

好啦,先运行服务器端js,再运行客户端服务器js,在浏览器输入IP和端口号输入文字,就可以看到效果哦,为了效果更好可以多开几个窗口哦

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