I can't understand a lot of WebSockets on the Internet. I have to watch a video to understand them
Video link: https://blog.csdn.net/QQ408896436/article/details/81606553
The following are all based on the steps of the teacher
First open cmd or powershell, type cd to enter the server address, and then type NPM install nodejs websocket
And nodejs installation address: https://nodejs.org/en/
After the installation is successful, create a new js under nodejs websocket
js server code:
var ws = require('nodejs-websocket'); var port=3000 var server = ws.createServer(function(conn){ //Triggered by connection// //Install NPM install nodejs websocket in server cmd// console.log('new connection'); conn.on("text",function(str){ // Receive message trigger receive// console.log("received"+str) boardcast(str) // Broadcast message// conn.sendText(str) // Send data// }) conn.on("close",function(code,reason){ // Disconnect trigger// console.log("connection closed") }) conn.on("error",function(err){ // Error triggered// console.log("header err") console.log(err) }) function boardcast(str){ // Broadcast / / // server.connections saves each connected user// server.connections.forEach(function(conn){ // . forEach is to call every element in the array// conn.sendText(str) }) } }).listen(port) console.log("websocket server listen port is" + port)
Next let's look at the client's general code:
<html> <head> <title>first socket</title> </head> <body> <h1>myfitst room</h1> <input type="text" id="snedTxt" /> <button id="sendb">Send out</button> <div id="recv"></div> <script type="text/javascript"> var ws = new WebSocket("ws://localhost:3000 / "); / / set the server address// ws.onopen=function(){ // onopen connection trigger// console.log("websocket open"); document.getElementById("recv").innerHTML="Connected"; // innerHTML can be obtained or inserted// } ws.onclose=function(){ // On close off trigger// console.log("websocket close"); } ws.onmessage =function(e){ // onmessage receives information trigger// console.log(e.data); document.getElementById("recv").innerHTML = e.data; } document.getElementById("sendb").onclick=function(){ // If the button with monitoring id = sendb triggers onclick, the data send will be sent// var txt = document.getElementById("snedTxt").value; ws.send(txt); } </script> </body> </html>
html runs directly
For js, cmd cd is required to go to the root directory and type the node file name. js
It's a success