思路整理
webSocket是服务器向客户端发送信息的一种手段
这里是 更多关于 webSocket 的内容
如果想要了解更多关于 nodeJS 中的webSocket内容,点击这里
开始之前,我们需要新建两个客户端和一个服务端,
服务端负责保存与客户端的连接并且在双方都在线上之后传输双方的讯息
客户端需要建立与服务器的连接然后通过指定方式声明自己的身份,然后开始 聊天
服务端
编写前要有 nodejs-websocket 包,可通过 npm i --save nodejs-websocket 安装
大体步骤:
新建服务器 ⇒
监听连接中的事件 ⇒
如果双方都建立过连接就向另一方发送讯息 ⇒
否则验证连接的口令是否正确,正确则将连接保存起来并视为以上线
let ws = require("nodejs-websocket");let chatA = null,chatB = null;
console.log(ws);
ws.createServer((conn) => {// 收到文本请求conn.on("text", (msg) => {// 如果双方都建立了连接,可以通信if (chatA && chatB) {if (conn === chatA) {// 向另一个连接发讯息chatB.send(msg)} else {chatA.send(msg)}return}// 有人不在线上,判断登录口令if (msg === "chatA token") {// 保存连接以判断是否上线与发送讯息chatA = conn;return}if (msg === "chatB token") {chatB = conn;}})conn.on("close", () => {})conn.on("error", (code, reason) => {console.log("exit with error code " + code + ", reason:" + reason);})
}).listen(8888) // 监听 8888 端口
客户端
大体步骤:
建立于服务器 localhost:8888 的连接(上方监听了端口 8888) ⇒
发出对应的登录口令 ⇒
点击发送按钮将文本框内容获取,将其放在聊天框中并发送请求,随后清空文本 ⇒
收到服务器信息后展现在聊天框中
关键代码:
let chatWindow = document.querySelector(".chat-window"), // 聊天框msgbox = document.querySelector("#my_msg"), // 输入框btn = document.querySelector("button"), // 发送按钮ws = new WebSocket("ws://localhost:8888"); // 与服务器建立连接if (window.WebSocket) {// 如果支持websocketws.onopen = () => {console.log("连接成功")// 发送对应口令以登录 在上面的 server端代码中,它们是 chatA token / chatB tokenws.send("chatA token")}ws.onclose = () => {console.log("连接关闭")}ws.onerror = () => {console.log("连接出错")}btn.addEventListener("click", (e) => {// 获取聊天框内容,向聊天框中添加后发送内容并清空聊天框let msg = msgbox.value;newMSG(msg, true)ws.send(msg)msgbox.value = ""})ws.onmessage = (e) => {newMSG(e.data)}function newMSG(msg, isSender = false) {let html = document.createElement("span")html.innerText = msghtml.classList = [isSender ? "senderMSG" : "reciverMSG"];chatWindow.appendChild(html)}}
效果展示
另外一个客户端的代码 除了登录口令换成了 chatB token 其他都是一致的
全部代码
<!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>Document</title><style>html,body {width: 100%;height: 100%;padding: 0;margin: 0;color: #eee;background-color: black;}.fullbox {width: 100%;height: 100%;}.chat-window {height: 80%;width: 100%;border: #eee 1px solid;}.input-session {height: 19%;width: 100%;border: #eee 1px solid;display: flex;justify-content: space-between;align-items: center;}.input-session>textarea {width: 80%;height: 100%;border: #eee 1px solid;color: #eee;background-color: black;padding: 2% 6%;box-sizing: border-box;}.input-session>button {height: 100%;width: 20%;text-align: center;border-radius: 5px;color: #eee;background-color: blue;cursor: pointer;}span {display: block;padding: 10px 5px;color: #eee;border-radius: 5px;margin: 10px;width: fit-content;position: relative;}.senderMSG {text-align: right;right: 10;}.reciverMSG {text-align: left;left: 10;}</style>
</head><body><div class="fullbox"><div class="chat-window"></div><div class="input-session"><textarea name="msgbox" id="my_msg" cols="30" rows="10"></textarea><button>SEND</button></div></div><script>let chatWindow = document.querySelector(".chat-window"),msgbox = document.querySelector("#my_msg"),btn = document.querySelector("button"),ws = new WebSocket("ws://localhost:8888"); // connect to serverif (window.WebSocket) {// support websocketws.onopen = () => {console.log("连接成功")ws.send("chatA token")}ws.onclose = () => {console.log("连接关闭")}ws.onerror = () => {console.log("连接出错")}// add btn click eventbtn.addEventListener("click", (e) => {// add new element to chat window add send msg to scocketlet msg = msgbox.value;newMSG(msg, true)ws.send(msg)msgbox.value = ""})ws.onmessage = (e) => {newMSG(e.data)}function newMSG(msg, isSender = false) {let html = document.createElement("span")html.innerText = msghtml.classList = [isSender ? "senderMSG" : "reciverMSG"];chatWindow.appendChild(html)}}</script>
</body></html>