The principle of chat room: client A sends messages -> server receives messages -> server actively sends messages to client B -> client B receives messages
HTTP request and response on the client or server are generally implemented based on HTTP. However, THE limitations of HTTP are as follows: Only the client can send a request, and the server responds to the request and returns data for one-way data transmission. WebSocket is a protocol for full-duplex communication over a single TCP connection. Common understanding: a protocol for bidirectional data transmission between the client and the server WebSocket features: 1. There is no source restriction, the client can communicate with any server; 2. The protocol header is ws(WSS is the encrypted identifier), for example, ws://localhost:8080. 3. Mainstream browsers support WebSocketCopy the code
Client implementation:
1. Create a WebSocket object and enable WebSocket
Var webSocket = new webSocket (url,[protocal]) //url -- Specifies the url of the connection -- Acceptable subprotocolCopy the code
2. Trigger the Event of the WebSocket object to implement the connection
Websocket.open = function (){websocket.send (){websocket.message = function (){websocket.message = function (){websocket.message = function (){websocket.message = function () ... } websocket. error = function (){ } websocket.close = function (){websocket.close ()}Copy the code
Node.js ws module implementation server:
1. Import the WS module, reference the Server class, and instantiate it
const WebSocket = require('ws').Server
wss = new WebSocket({host:'loaclhost',port:8080})
Copy the code
2. Invoke the webSocket object method to transfer data
Ws.on ('connection',function(ws){ws.on('message',function(message){client.send() // Send data to client})})Copy the code
Specific implementation code:
<style> img {width: 100px; height: 100px; border-radius: 50%; position: absolute; top: 30%; left: 50%; margin-top: -50px; margin-left: -50px; } input { width: 200px; border: 1px solid #ccc; padding: 7px 0px; border-radius: 3px; padding-left: 5px; box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; position: absolute; top: 42%; left: 50%; margin-left: -100px; } input:focus { border: none; outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(102, 175, 233, .6); Box-shadow: inset 0 1px 1px rgba(0, 0, 0,.075), 0 08px rgba(102, 175, 233,.6)}. position: relative; display: inline-block; font-weight: 400; white-space: nowrap; text-align: center; background-image: none; border: 1px solid transparent; Box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015); cursor: pointer; transition: all .3s cubic-bezier(.645, .045, .355, 1); user-select: none; touch-action: manipulation; height: 32px; padding: 0 15px; font-size: 14px; border-radius: 4px; Color: rgba(0, 0, 0, 0.65); background-color: #fff; border-color: #d9d9d9; } .ant-btn-primary { width: 60px; color: #fff; background-color: #1890ff; border-color: #1890ff; Text-shadow: 0-1px 0 rgba(0, 0, 0, 0.12); Box-shadow: 0 2px 0 rgba(0, 0, 0, 0.045); position: absolute; top: 50%; left: 50%; margin-left: -30px; } </style> <body> <img src="./avatar.jpg" alt=""> <input type="text"> <button class="ant-btn ant-btn-primary" onclick='toChat()' >Go</button> </body> <script> function toChat(){ var name = document.getElementsByTagName('input')[0].value window.location.href=`./webSocket.html?name=${name}` } </script>Copy the code
/ / get the url parameter function getQueryString (name) {let reg = new RegExp (" (^ | &) "+ name +" = (/ ^ & *) (& | $) "and" I "); let r = window.location.search.substr(1).match(reg); if (r ! = null) { return decodeURIComponent(r[2]); }; return null; }Copy the code
Chat room HTML file, <body> <div class="chat"> <div class="inputBox"> <input type="text" /> <button class="ant-btn ant-btn-primary" </button> </div> </body> <script SRC ='./ geturl.js '></script> <script> var user = {name: getQueryString('name'), message: [], } var flag = true; var webSocket = new WebSocket("ws://localhost:8080"); function send() { let value = document.getElementsByTagName('input')[0].value webSocket.onopen(event, value) return document.getElementsByTagName('input')[0].value = '' } webSocket.onopen = function (event, value) { if (value == undefined) { webSocket.send(JSON.stringify(user.name)) return flag = true } else { user.message.push(value) webSocket.send(JSON.stringify(user)) return flag = false } } webSocket.onmessage = function (evt) { var box = document.createElement("div") box.setAttribute("class", Var avatar = document.createElement("img") avatar.src = './avatar.jpg' var ele = ' document.createElement("div") ele.setAttribute("class", "message") if (flag && typeof JSON.parse(evt.data) == 'string') { var welcome = document.createElement("div") welcome.setAttribute('class', 'welcome') document. The body. The appendChild (welcome) welcome. InnerHTML = ` ${JSON. Parse (evt) data)} to join chat rooms `} else {ele. InnerHTML = JSON.parse(evt.data).message[JSON.parse(evt.data).message.length - 1] if (user.name == JSON.parse(evt.data).name) { box.style.justifyContent = 'flex-end' box.appendChild(ele) box.appendChild(avatar) } else { box.appendChild(avatar) box.appendChild(ele) } } document.body.appendChild(box) } webSocket.onclose = function (evt) { console.log("connection closed") } </script>Copy the code
The simplest basic implementation is such, the complete chat room needs to consider more details, for the time being not a implementation