nodeJS+websocket创建聊天室

前言
nodeJS + websocket创建一个简易的多人聊天室

客户端
HTML

<div class="container">
	<header>
		<img src="./img/edit2.png" >
		<h3>Live</h3>
		<div class="user"></div>
		<a style="position: absolute;right: 5px;" href="index.html">返回</a>
	</header>
	<section>
		<div class="chat-record">
			<ul class="chat-show">
				<!-- <li class="left">
					<h6 class="name">张三</h6>
					<p class="content">Hgsdh没收到过可是可是sdhfh</p>
				</li>
				<li class="right">
					<h6 class="name"></h6>
					<p class="content">Hgsdh没收到过可是可是sdhfh</p>
				</li> -->
			</ul>
		</div>
	</section>
	<footer>
		<div class="enter-box">
			<div class="enter">
				<textarea class="chat-input" onkeydown="keydownEvent(event)" onkeyup="keyupEvent(event)" ></textarea>
				<div class="bottom">
					<button type="button" onclick="sendChat()" >发送</button>
				</div>
			</div>
		</div>
	</footer>
</div>

JS

let wss = null;
let user = '';
// 初始化
function init(){
	let uuid = getCookie('uuid');
	// 设置随机用户id
	user = uuid || Math.random().toString(36).slice(-6);
	setCookie('uuid', user);
	document.querySelector('.user').innerHTML = user;
	wss = new ConnectWebsocket(user);
}
init();
wss.message((ws, data)=>{
	if(!data.text) return;
	render(data);
})
let shift = false;
// 停止换行状态
function keyupEvent(e){
	if(e.keyCode === 16){
		shift = false;
	}
}
// 发送|换行 聊天信息
function keydownEvent(e){
	if(e.keyCode === 16){
		shift = true;
	}
	if(shift && e.keyCode === 13){
		console.log('换行');
	}else if(e.keyCode === 13){
		e.preventDefault();
		console.log('发送');
		let text = e.target.value.replace(/\n/g, '
'
); sendChat(text); } } // 发送聊天信息 function sendChat(context){ let el = document.querySelector('.chat-input'); let text = context || el.value; el.value = ''; if(!text.trim()) return; wss.send({uuid: user, text}) } // 渲染聊天信息 function render({uuid, text}){ let el = document.querySelector('.chat-show'); let newEl = document.createElement('li'); // 判断是本人消息还是其他人 if(uuid === user){ newEl.classList.add('right'); }else{ newEl.classList.add('left'); } let htmlStr = `
${uuid}

${text}

`
; newEl.innerHTML = htmlStr; el.appendChild(newEl); // 消息窗口滚动到最下面,时刻显示最新消息 let scrollEl = document.querySelector('section'); scrollEl.scrollTop = scrollEl.scrollHeight; } // 创建websocket连接 function ConnectWebsocket(uuid) { // 创建连接的时候携带用户ID绑定 let url = `ws://localhost:8999/websocket/uuid?uuid=${uuid}`; var ws = new WebSocket(url); ws.onopen = function () { console.log("连接成功!"); ws.send(JSON.stringify({uuid})); }; ws.onclose = function () { console.log("连接已关闭...正在重连..."); ConnectWebsocket(uuid); }; this.message = (cb) =>{ ws.onmessage = res => { var data = JSON.parse(res.data); cb && cb(ws, data) }; } this.send = (data) =>{ ws.send(JSON.stringify(data)); } } // 获取cookie function getCookie(key){ let str = document.cookie || ''; if(str === '') return ''; let arr = str.split('; '); let cookie = {}; arr.forEach(it => { let a = it.split('='); cookie[a[0]] = a[1]; }) return cookie[key] } // 设置cookie function setCookie(key, value, time = 1){ let date = new Date(); let exdays = date.getTime() + time * 24 * 60 * 60 * 1000; date.setTime(exdays); let expires = `expires=${date.toUTCString()}`; let str = `${key}=${value};${expires}`; document.cookie = str; } // 移除cookie function removeCookie(key){ setCookie(key, '', -1); }

服务端

这里服务端需要设置两个端口:一个是访问页面所需的http端口,一个是创建websocket的ws端口;http端口的服务创建方式我之前的博文有写过,这里只讲ws服务端的创建

// 首先安装websocket的ws包
npm install ws


// 编写服务 socket.js
const url = require('url');
const { WebSocketServer } = require('ws')

const wss = new WebSocketServer({
	port: 8999
})

// 服务端会和每一个客户端都创建一个ws连接,所以需要根据id将所有的ws收集起来
// 多人聊天室和两人聊天不同,这里只实现简单的多人聊天
let wsList = {};
wss.on('connection', (ws, req)=>{
	// console.log('客户端已连接', req.socket.remoteAddress);
	let query = url.parse(req.url).query;
	// key为客户端传参的uuid
	let key = query.split('=')[1];
	// 将创建的连接收集起来
	wsList[key] = ws;
	ws.on('message', data =>{
		// console.log(data);
		let info = JSON.parse(data.toString());
		console.log('收到客户端发送的消息:', info)
		if(info.text){
			for(let a in wsList){
				wsList[a].send(JSON.stringify(info))
			}
		}
	})
})


// 运行
node socket.js

ok,一个简单的多人聊天室就搭建好了,最后把css也放这里吧

html, body{
	margin: 0;
	padding: 0;
}
ul, li{
	text-decoration: none;
	list-style: none;
	padding: 0;
}
textarea:focus{
	border: none;
	outline: none;
}
form{
	padding: 20px;
}
div{
	padding: 10px;
}
.container{
	max-width: 768px;
	margin: auto;
	padding: 0 10px;
	height: 100vh;
	box-shadow: 0 0 3px 2px #eee;
	background-color: #f7f7f7;
	overflow: hidden;
}
header{
	position: relative;
	display: flex;
	align-items: center;
	padding: 5px 0;
	border-bottom: 1px solid #F1F1F1;
	height: 50px;
	box-sizing: border-box;
}
header img{
	width: auto;
	height: 80%;
	margin: 0 5px;
}
header h3{
	margin: 0;
}
footer{
	height: 120px;
	border-top: 1px solid #eee;
	box-sizing: border-box;
}
footer div{
	padding: 0;
}
footer .enter{
	width: 100%;
	height: 100%;
}
.enter textarea{
	display: block;
	width: 100%;
	height: 80px;
	background-color: #fff;
	box-sizing: border-box;
	padding: 5px;
	border: none;
	resize: none;
}
.enter .bottom{
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: flex-end;
}
section{
	height: calc(100vh - 170px);
	overflow: auto;
	background-color: #fff;
}
section li{
	display: flex;
	flex-direction: column;
	margin-bottom: 20px;
	overflow: hidden;
}
section li.left{
	align-items: flex-start;
}
section li.right{
	align-items: flex-end;
}
li.left p{
	background-color: #EEEEEE;
}
li.right p{
	background-color: rgba(210,191,255, .3);
}
section h6{
	padding: 4px;
	font-size: 14px;
	margin: 0;
}
section li p{
	margin: 5px 0;
	padding: 4px 8px;
	color: #444;
	border-radius: 4px;
}

你可能感兴趣的:(node,websocket,javascript,前端,node.js)