nodejs实现实时聊天,超简单||WebSocket
首先初始化一个项目
npm init
安装ws模块
npm install ws --save
编辑服务端代码
//新建server.js文件
// 服务器端
let WBSokcet = require("ws").Server;
let ws = new WBSokcet({ port: 9090 });
let clients = [];
ws.on("connection", function(client) {
// 有人链接了
// 把client保存到数组里
clients.push(client);
// 客户端(用send函数)发送信息后,会触发message事件
client.on("message", function(str) {
console.log("str", str);
// 把收到的信息,分发给其它客户端
broadcast(str);
})
});
// 把收到的信息分发给所有的客户端
function broadcast(str) {
console.log("broadcast");
clients.forEach(item => {
// 给某个客户端发送信息
item.send(str);
});
}
现在可以把服务跑起来了
node server.js
新建连接文件
页面比较粗糙,仅实现了功能,可以根据需求自己去美化
新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ws</title>
</head>
<body>
<div id="chatroom" style="width:400px;height:300px;overflow:auto;">
</div>
<input type="text" id="sayinput" value="123">
<input type="button" name="send" id="sendbutton" value="发送">
</body>
</html>
<script type="text/javascript">
//这里改成你的ip端口号与server.js相对于
let ws = new WebSocket("ws://192.168.1.4:9090/");
// 链接建立打开后
ws.onopen = function () {
ws.send("大家好");
}
// 服务器端发送信息(用send函数)后,触发onmessage事件
ws.onmessage = function (event) {
console.log("event", event);
// 把str放在html页面上。
chatroom.innerHTML += event.data + "<br/>"
}
// 获取文本框
let oText = document.getElementById("sayinput");
function send() {
ws.send(oText.value);
oText.value = '';
}
document.getElementById("sendbutton").onclick = function () {
send();
}
</script>
打开index.html就可以看到效果