前端+nodejs实现聊天功能(一)

在后端

	let ws = require("nodejs-websocket");
	let chatA = null,chatB = null;
	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端口

前端

	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>Documenttitle>
    	<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>SENDbutton>
        	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 server
        if (window.WebSocket) {
            // support websocket
            ws.onopen = () => {
                console.log("连接成功")
                ws.send("chatB token")  //另外一个页面改为ws.send("chatA token")
            }
            ws.onclose = () => {
                console.log("连接关闭")
            }
            ws.onerror = () => {
                console.log("连接出错")
            }
            // add btn click event
            btn.addEventListener("click", (e) => {
                // add new element to chat window add send msg to scocket
                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 = msg
                html.classList = [isSender ? "senderMSG" : "reciverMSG"];
                chatWindow.appendChild(html)
            }
        }
    script>
	body>

	html>

启动nodejs后台,分别打开A和B页面,就可以实现简单的聊天

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