1.后端下包
npm i koa koa-websocket
2.后端代码
// 聊天室
const Koa = require("koa");
const WebSocket = require("koa-websocket");
const app = WebSocket(new Koa());
let ctxs = [];
// 简单的消息收发
app.ws.use((ctx, next) => {
// 接收接入多个用户(每一个ctx代表一个用户)
ctxs.push(ctx);
ctx.websocket.on("message", (message) => {
console.log(message, "message");
for (let i = 0; i < ctxs.length; i++) {
if (ctx == ctxs[i]) continue;
ctxs[i].websocket.send(message.toString());
}
});
ctx.websocket.on("close", (message) => {
// 关闭时清除相关数据,防止出错
let index = ctxs.indexOf(ctx);
ctxs.splice(index, 1);
});
});
app.listen(3001, () => console.log("http://localhost:3001"));
3.前端代码
html页面
import React from 'react'
import './index.moudle.scss'
import NavBar from '@/components/navBar';
//实例化 WebSocket 并且连接服务器
const webSocket = new WebSocket("ws://localhost:3001");
/* 接收到服务端的消息时 */
webSocket.onmessage = function (msg) {
console.log("接收到新消息:" + msg.data);
const oFriendItem = document.createElement('div');
oFriendItem.className = 'friedns-item';
const oSpan = document.createElement('span');
oSpan.className = 'friedns';
const message = document.createTextNode(msg.data);
oSpan.appendChild(message);
oFriendItem.appendChild(oSpan);
(document.getElementById('chatContent') as HTMLElement).appendChild(oFriendItem);
};
// 关闭连接
webSocket.onclose = function () {
console.log("关闭连接");
};
function Socket() {
// 发送
const sendBtn = () => {
const str = (document.getElementById('content') as HTMLInputElement).value
const oMeItem = document.createElement('div');
oMeItem.className = 'me-item';
const oSpan = document.createElement('span');
oSpan.className = 'me';
const msg = document.createTextNode((document.getElementById('content') as HTMLInputElement).value);
oSpan.appendChild(msg);
oMeItem.appendChild(oSpan);
(document.getElementById('chatContent') as HTMLElement).appendChild(oMeItem);
// 发送后清空消息框
(document.getElementById('content') as HTMLInputElement).value = '';
webSocket.send(str);
}
// 关闭连接
const closeBtn = () => {
webSocket.close();
}
return (
<div className="chat-room">
<NavBar title='聊天室' type='back' />
<div className="chat-content" id="chatContent">
</div>
<div className="chat-op">
<input type="text" id="content" />
<input type="button" value="发送" onClick={sendBtn} id="send" />
<input type="button" value="关闭" onClick={closeBtn} id="close" />
</div>
</div>
)
}
export default Socket
.chat-room {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.chat-content {
width: 100%;
flex: 1;
background: #eee;
overflow: auto;
}
.chat-op {
width: 100%;
height: 40px;
line-height: 40px;
position: fixed;
bottom: 0;
left: 0;
}
.me-item {
text-align: right;
}