Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Recall from our previous article, “Why Websocket?” , to understand the characteristics of Websocket and communication principle, we then look at the Websocket server and client implementation.
Websocket server and client implementation
After combing the communication process before, we will WebSocket communication basic mechanism has said almost, in order to facilitate you quickly into the actual combat stage, we temporarily abandon pure handwriting implementation, directly choose to use the old WebSocket library: WebSocket-Nodehttps:github.com/theturtle32/WebSocket-Node
A quick introduction to Websocket-Node, how old is it?
The package name for NPM is simply “WebSocket”. Once, we xiling old wet after seeing gave two words of evaluation: “rampant”.
The library is implemented entirely in JavaScript and contains both client-side and server-side instances. In addition to supporting version 13 of the Websocket protocol we mentioned earlier, it also supports the old version 8 of the Websocket protocol, which is excellent.
Next, let’s look at how to implement a Websocket service with websocket-Node.
The service side
After installing NPM install websocket, create server run file WS-server.js, the code is as follows, please read the code and comments carefully:
=== var Websocket = require(' Websocket '). Server var HTTP = require(' HTTP ') Var httpServer = http.createserver ().listen(8080,function(){console.log('http://127.0.0.1:8080')}) // is created as a first handshake link Var wsServer = new webSocket ({// configure the dependent handshake HTTP server :httpServer, AutoAcceptConnections: false})/var/save link pool conArr = [] / / surveillance ws request event wsServer on (' request ', function (request) {/ / for a link example Connection. on('message',function(MSG){var connection = request.accept(); var connection = request.accept(); Console. log(MSG) // Loop connection pool, push broadcast message to client for(let I = 0; i<conArr.length; I ++){conArr[I].send(msg.utf8data)}})}Copy the code
One item beyond description: One item for a pretty item will be plus-one item from the code comment (●’◡’●)
After running the code file, the command line process will be occupied and the listening port will also be occupied, which proves that the server is running successfully. If neither one is occupied, what are you thinking? Failed, Treasure son…
The client
If the server starts successfully, how can I use the client to create a link to view it? There is a Websocket client called WebsocketMan. If you are interested, you can download it and try it out.
But the handsome guy like me, generally write their own client 🙂
The client side of Websocket doesn’t have any technical difficulties other than the browser API calls. As long as you are clear about the communication mechanism, there is no problem with this, because it is very simple, we will go straight to pure handwriting, if you want to use a Websocket-Node client, it is even easier.
Of course, read the manual before writing, otherwise how do you know what the apis are?
Here, the manual address for you: developer.mozilla.org/zh-CN/docs/…
You watch, I don’t hesitate, straight to work…
<body> <div id=" MSG "></div> <input type="text" id="text"> <input type="button" value=" send "> // Call the webSocket object to establish a connection: Ws/WSS (encrypted):// IP :port (string) var websocket = new webSocket ('ws://127.0.0.1:8080') // console.log(websocket.readystate) // Websocket.onopen = function () {readyState = function () {websocket.onOpen = function () { Console. log(websocket.readystate)} function send() {var text = document.getelementById ('text').value Websocket. onMessage = function (back) {console.log(back.data)} // Listen for connection error messages // websocket.onerror = function (evt, e) { // console.log('Error occured: ' + evt.data); / /}; // websocket.onclose = function (evt) {// console.log("Disconnected"); / /}; </script> </body>Copy the code
One item beyond description: One item for a pretty item will be plus-one item from the code comment (●’◡’●)
At this point, a complete Websocket communication is established and two-way communication is possible.
Websocket-node is really good to use, but the function is also relatively simple, you need to have a certain understanding of the Websocket mechanism, to achieve the corresponding ability. What if I don’t know anything about Websocket, but I want to have a chat room?
Refers to! On! Can!!!! Line!
Socket.IO
One of the most powerful and user-friendly websocket libraries that basically shield the concept of Websocket. You don’t need to know much about Websockets, just follow the API provided in socket. IO to implement a webSocket communication.
Note: programmers need to “de-core”.
- It is strongly not recommended to use Websocket if you do not know Websocket.
- In a production environment, it is highly recommended.
The service side
const { createServer } = require("http"); const { Server } = require("socket.io"); const httpServer = createServer(); const io = new Server(httpServer, { cors: { origin: "*", methods: ["GET", "POST"] } }); io.on("connection", (socket) => { socket.on('sendMsg',(data)=>{ io.emit('pushMsg',data) }) }); Httpserver.listen (3000, function () {console.log('http://127.0.0.1:3000')});Copy the code
The client
<! 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 > < script SRC =" https://cdn.socket.io/4.2.0/socket.io.min.js" integrity="sha384-PiBR5S00EtOj2Lto9Uu81cmoyZqR57XcOna1oAuVuIEjzj0wpqDVfD0JA9eXlRsj" crossorigin="anonymous"></script> </head> <body> <input type="text" id="text"> <input type="button" value=" send "onclick="send()" IO. Connect ('http://127.0.0.1:3000') function send() {var text = document.getelementById ('text').value socket.emit('sendMsg', text) } socket.on('pushMsg', (data) => { console.log(data) }) </script> </body> </html>Copy the code
Nothing to explain, just write the socket. IO API.
Bye bye ヾ (, omega, `) o
As I have heard from my teachers, those who have machinery will have organic work, and those who have organic work will have organic heart. Machine heart in the chest, is pure white unprepared. — Chuang Zi · Tiandi
The resources
HTML5 WebSocket Authoritative Guide, China Machine Press, March 2014, 1st edition
www.ruanyifeng.com/blog/2017/0…
www.cnblogs.com/hustskyking…
www.cnblogs.com/jingmoxukon…
zhuanlan.zhihu.com/p/23467317
Developer.mozilla.org/zh-CN/docs/…
Library:
socket.io/docs/
Github.com/theturtle32…