此案例仅为简单基础案例展示。
# chat 聊天室
## 项目结构
js
entry.html
index.html
## 启动项目
cd chat
npm i
npm run dev
http://localhost:3000/
## 使用
分别用两个浏览器打开 http://localhost:3000/
# server 本机服务模拟
## 项目结构
index.js
## 启动服务
cd server
npm i -g nodemon (如已全局安装过则无需安装)
npm i
nodemon index.js# chat 聊天室
## 项目结构
-| js
- entry.js
- index.js
- entry.html
- index.html
- package.json
## 启动项目
cd chat
npm i
npm run dev
http://localhost:3000/
## 使用
分别用两个浏览器打开 http://localhost:3000/
# server 本机服务模拟
## 项目结构
- index.js
- package.json
## 启动服务
cd server
npm i -g nodemon (如已全局安装过则无需安装)
npm i
nodemon index.js
server / index.js
const Ws = require('ws');
((Ws) => {
const server = new Ws.Server({port: 8000});
const init = () => {
bindEvent();
};
function bindEvent() {
server.on('open', openHandler);
server.on('close', closeHandler);
server.on('error', errorHandler);
server.on('connection', connectionHandler);
};
function openHandler(e) {
console.log('open', e);
};
function closeHandler(e) {
console.log('close', e);
};
function errorHandler(e) {
console.log(e);
};
function connectionHandler(ws) {
ws.on('message', handlerSend);
};
function handlerSend(message) {
console.log(message);
const mes = JSON.parse(message)
server.clients.forEach((i)=>{
i.send(JSON.stringify(mes));
})
};
init();
})(Ws);
server / package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ws": "^8.13.0"
}
}
chat / entry.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>登录</title>
</head>
<body>
<input id="username"/> <button id="enter">登录</button>
<script src="./js/entry.js"></script>
</body>
</html>
chat / 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>聊天室</title>
</head>
<body>
<input type="text" id="message"> <button id="send">发送</button>
<ul id="messageList"></ul>
<script src="./js/index.js"></script>
</body>
</html>
chat / js / entry.js
((doc, Storage, location) => {
const userName = doc.querySelector('#username');
const enterBtn = doc.querySelector('#enter');
const init = () => {
bindEvent();
};
function bindEvent() {
enterBtn.addEventListener('click', enterBtnClickFun, false);
};
function enterBtnClickFun() {
const user = userName.value.trim();
if(user.length === 0) return alert('请输入用户名');
Storage.setItem('username', user);
location.href = 'index.html';
}
init();
})(document, localStorage, location);
chat / js / index.js
((doc, Storage, location, WebSocket) => {
const message = doc.querySelector('#message');
const messageList = doc.querySelector('#messageList');
const sendBtn = doc.querySelector('#send');
const ws = new WebSocket('ws:localhost:8000');
const init = () => {
const user = Storage.getItem('username');
console.log(user,'user')
if(!user) return location.href = 'entry.html';
bindHandler();
};
function bindHandler() {
sendBtn.addEventListener('click', sendBtnClickFun, false);
ws.addEventListener('open', openHandler, false);
ws.addEventListener('close', closeHandler, false);
ws.addEventListener('error', errorHandler, false);
ws.addEventListener('message', messageHandler, false);
};
function openHandler(e) {
console.log('已链接');
};
function closeHandler(e) {
console.log('已断开');
};
function errorHandler(e) {
console.log('出错');
};
function messageHandler(e) {
console.log('发送信息',e);
const mesData = JSON.parse(e.data);
const item = doc.createElement('li');
item.innerHTML = `<p>${mesData.user} ${mesData.dateTime}</p>
<p>${mesData.text}</p>`
messageList.appendChild(item)
};
function sendBtnClickFun() {
const mes = message.value.trim();
if(mes.length === 0) return alert('请输入消息');
const params = JSON.stringify({
user: Storage.getItem('username'),
dateTime: new Date().getTime(),
text: mes
})
ws.send(params)
message.value = '';
}
init();
})(document, localStorage, location, WebSocket)
chat / package.json
{
"name": "chat",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"vite": "^1.0.0-rc.13"
},
"scripts": {
"dev": "vite"
},
"keywords": [],
"author": "",
"license": "ISC"
}