文件目录如下:
?
?使用nodemon热更新启动server.js
目的是在局域网内能访问到聊天界面
nodemon server.js
?代码如下
const Koa = require('koa')
const path = require('path')
const static = require('koa-static')
const Router = require('koa-router')
let router = new Router()
const app = new Koa()
const staticPath = './static'
app.use(static(
path.join( __dirname, staticPath)
))
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(6677)
使用nodemon热更新启动websocket.js
启动websocket服务
nodemon websocket.js
?代码如下
const ws = require('nodejs-websocket');
const PORT = 6678
const arr = []
const server = ws.createServer(connect => {
const useId = new Date().getTime()
connect.userName = `用户${useId}`;
arr.push({
userName:connect.userName,
value: '加入聊天室',
connect,
})
broadcast(arr)
connect.on('text', data => {
const params = {
connect,
userName:connect.userName,
value: data,
}
arr.push(params)
broadcast(arr)
});
//连接关闭触发close事件
connect.on('close',()=>{
arr.push({
userName:connect.userName,
value: '离开了聊天室',
})
});
//注册error事件,用户端口后就会触发该异常
connect.on('error',()=>{
console.log('用户连接异常');
});
});
const broadcast = (arr) => {
const params = arr.map(({userName,value})=>({
userName,
value
}))
server.connections.forEach(item => {
item.send(JSON.stringify(params));
});
}
server.listen(PORT);
连同一wifi下,所有人访问这个地址进入聊天
http://ip:6677/index.html
index.html?代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.bodys{
width: 400px;
margin: 0 auto;
}
#content {
width: 400px;
height: 600px;
border: 1px solid #000;
overflow-y: scroll;
}
</style>
<body>
<div class="bodys">
<div id="content"></div>
<input id="xiaoming" placeholder="请输入" />
<button id="submit">发送</button>
</div>
</body>
<script>
let input = document.getElementById('xiaoming');
let button = document.getElementById('submit');
let div = document.getElementById('content');
//创建WebSocket('WebSocket服务器地址')
//下一行的ip修改一下
let socket = new WebSocket('ws://ip:6678/');
// let socket = new WebSocket('ws://localhost:6678/');
//监听WebSocket事件 open和WebSocket服务器连接成功触发
socket.addEventListener('open',()=>{
console.log('连接成功')
});
input.addEventListener('keydown',(e)=>{
if(e.keyCode===13){
let value = input.value;
input.value = ''
socket.send(value);
}
})
//给webSocket发送消息
button.addEventListener('click',()=>{
let value = input.value;
input.value = ''
socket.send(value);
});
//接受websocket服务的消息
socket.addEventListener('message',(msg)=>{
const data = JSON.parse(msg.data)
let str = ''
data.forEach(item=>{
str+=`<div>${item.userName}:${item.value}</div>`
})
//把消息显示到div
div.innerHTML = str
div.scrollTop = div.scrollHeight;
});
//端口服务
socket.addEventListener('close',()=>{
console.log('服务断开');
});
</script>
</html>
注意IP的修改
|