The native WebSocket API is not very convenient to use. When we use it, it encapsulates the webSocket interface well, provides a simpler and more flexible interface, and provides backward compatibility for browsers that do not support webSocket.
- Server code
- Store different objects according to the messages sent from different clients
- Need to install npm i --save
- download
nodejs code
const socket = require(""); const http = require('http'); // Create a serviceconst server = ((req,res)=>{ // Allow all cross-domain requests ('Access-Control-Allow-Origin', '*'); (200,{'Content-Type':'text/html'}) ('') }).listen(8001) let pad = null,pc = null , padReady = false , pcReady = false; // connect(server).on('connection',(conn)=>{ ('message',(str)=>{ if(str==="Pad"){ pad = conn; padReady = true; ('Connected successfully'); } if(str==="PC"){ pc = conn; pcReady = true; } if(padReady&&pcReady){ if(str==='PC') str='I'm a PC interface' (str); } }) ("disconnection",(code, reason) => { ("Close the connection") }); })
Code
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .kuang { text-align: center; margin-top: 200px; } #mess { text-align: center } .value { width: 200px; height: 200px; border: 1px solid; text-align: center; line-height: 200px; display: inline-block; } </style> </head> <body> <div >Connecting...</div> <div class="kuang"> <div class="value" >aaaaaaa</div> <div class="value" >bbbbbbb</div> <div class="value" >ccccccc</div> </div> <script src="./js/"></script> <script> // Cross-domain address const socket = io('192.168.1.115:8001') ('connect', () => { // Connection is successful ('Pad') // Listen to the connection ('message', (msg) => { ('mess').innerHTML=msg // (msg) }) // Close the connection ('disconnect', () => { }) }) (".kuang").onclick = (e)=> { (); } </script> </body> </html>
Code
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .kuang { text-align: center; margin-top: 200px; } #mess { text-align: center } </style> </head> <body> <div ></div> <script src="./js/"></script> <script> var mess = ("mess"); // Cross-domain address // TODO: Note here: You cannot write 127.0.0.1 or localhost, otherwise other clients will not be able to access it. const socket = io('192.168.1.115:8001') ('connect', () => { // Connection is successful ('PC') // Listen to the connection ('message', (msg) => { = msg // (msg) }) // Close the connection ('disconnect', () => { }) }) </script> </body> </html>
The above is the detailed content of NodeJs [Enhanced Version] to implement cross-domain WebSocket instant messaging. For more information about NodeJs cross-domain WebSocket instant messaging, please follow my other related articles!