本文主要是介绍基于websocket实现Web群聊,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装node中ws模块
npm install ws
Node中处理代码
const WebSocket = require("ws");
const wsServer = new WebSocket.Server({port:3000});
var maps = new Map();
var number = 0;
var sendMessage = {};
wsServer.on('connection',(socket) => {console.log("Client Connected");number++;socket.userID = number;let client = {userID:socket.userID,Connection:socket}maps.set(socket.userID,client);sendMessage.type='enter';sendMessage.message="user"+socket.userID+"进来了!";broadCast(JSON.stringify(sendMessage));socket.on('message',(message) => {console.log('received:'+message);sendMessage.type='message';sendMessage.message="user"+socket.userID+":"+message+".";broadCast(JSON.stringify(sendMessage));});socket.on('close', () => {console.log('Connected Close');sendMessage.type='close';sendMessage.message="user"+socket.userID+" leave out!";maps.delete(socket.userID);broadCast(JSON.stringify(sendMessage));});function broadCast(message) {for(let val of maps.values()) {val.Connection.send(message);}}
});
页面代码:
<!DOCTYPE HTML>
<html>
<head><meta charset="UTF-8"/><title>websocket群聊</title>
</head>
<body><div id="app"><input type="text" id="text"/><button id="send">发送</button><div id="content"></div></div>
</body>
</html>
<script>var websocket = new WebSocket("ws://127.0.0.1:3000");var dataList = [];websocket.onopen = function (event) {console.log("正在建立连接...");}websocket.onclose = function (closeEvent) {console.log("连接正在关闭...");dataList = [];}websocket.onmessage = function (message) {console.log(message);let data = message.data;if (typeof data == "string") {data = JSON.parse(data);}//接受来自服务器发送的消息dataList.push(data);showMessage(dataList);}websocket.onerror = function (event) {console.log("连接发生错误");console.log(event);}function showMessage(data) {let html = "";for (let i =0;i<data.length;i++) {let type = data[i].type;if (type == 'enter') {html+="<div style='color:deepskyblue'>"+data[i].message+"</div>";} else if (type == 'message') {html+="<div style='color:black'>"+data[i].message+"</div>";} else if (type == 'close') {html+="<div style='color:red'>"+data[i].message+"</div>";}}//将元素动态显示到页面上document.querySelector('#content').innerHTML = html;}window.onbeforeunload = function (){websocket.close();}document.querySelector('#send').onclick = function() {let text = document.querySelector('#text').value;console.log(text);websocket.send(text);}</script>
实现效果
这篇关于基于websocket实现Web群聊的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!