当前位置:网站首页>Nodejs + websocket cycle small case
Nodejs + websocket cycle small case
2022-04-23 13:06:00 【It's never too late to be alone】
Start a project , Let's install one for the project first nodeJs Module , It's called nodejs-websocket ,
npm install nodejs-websocket
Server side
var ws = require("nodejs-websocket")
var index = 0;
let IndexNum;
var server = ws.createServer(function(conn) {
console.log("New connection")
//conn.on("***",function(){}) The binding event (***) And event handlers
conn.on("text", function(str) {
// event :“ text(str)” Send... When text is received .str Is a string
console.log(str);
if(str == 1 ){
IndexNum = setInterval(()=>{
let mes = {
};
mes.index = index++;
mes.number = parseInt (Math.random()*100);
//JSON.stringify(mes) Serialization object , Convert the type of object to string type
conn.sendText(JSON.stringify(mes));// Send the given string to the front end
},1000);
}else{
conn.sendText('erro');
}
})
conn.on("close", function(code) {
// Start closing the handshake ( Send close frame )
console.log(" close ",code);
clearInterval(IndexNum);
})
conn.on("error", function(err) {
// Issue when an error occurs . If the handshake doesn't work , Will also respond .
console.log(err);
})
}).listen(3000);// Server listening port 3000
console.log("websocket server running on port: 3000");
client
<body>
<button onclick="begin()"> Start </button>
<button onclick="stop()"> stop it </button>
<div class="box"></div>
<script type="text/javascript"> var websocket = new WebSocket("ws://localhost:3000/"); var box = document.getElementsByClassName('box')[0]; websocket.onopen = function() {
console.log(" Successful connection "); } websocket.onclose = function() {
console.log("websocket close"); } function begin(){
websocket.send(1); } function stop(){
websocket.close(); } // Only receive string parameters , So on the server side, it is said that the object can be used JSON Convert to a string first , Then turn it into an object here websocket.onmessage = function(e) {
let data = JSON.parse(e.data); let text = `<li> The first ${
data.index} Time , The number is ${
data.number};</li>` box.innerHTML += text; } </script>
</body>
版权声明
本文为[It's never too late to be alone]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231303465578.html
边栏推荐
- The use of dcast and melt in R language is simple and easy to understand
- Three channel ultrasonic ranging system based on 51 single chip microcomputer (timer ranging)
- filter()遍历Array异常友好
- AUTOSAR from introduction to mastery 100 lectures (83) - bootloader self refresh
- Timing role in the project
- Important knowledge of transport layer (interview, retest, final)
- 8 websites that should be known for product development to enhance work experience
- Free and open source charging pile Internet of things cloud platform
- 将opencv 图片转换为字节的方式
- MySQL -- 16. Data structure of index
猜你喜欢
拥抱机器视觉新蓝海,冀为好望开启数字经济发展新“冀”遇
100 GIS practical application cases (53) - making three-dimensional image map as the base map of urban spatial pattern analysis
CGC: contractual graph clustering for community detection and tracking
hbuilderx + uniapp 打包ipa提交App store踩坑记
[Blue Bridge Cup] April 17 provincial competition brushing training (the first three questions)
mysql8安装
MySQL -- 16. Data structure of index
Navicat远程连接数据库 出现 1130- Host xxx is not allowed to connect to this MySQL server错误
GIS practical tips (III) - how to add legend in CASS?
three. JS text ambiguity problem
随机推荐
21 days learning mongodb notes
5 free audio material websites, recommended collection
Timing role in the project
AUTOSAR from introduction to mastery 100 lectures (87) - key weapon of advanced EEA - AUTOSAR and DDS
Embrace the new blue ocean of machine vision and hope to open a new "Ji" encounter for the development of digital economy
拥抱机器视觉新蓝海,冀为好望开启数字经济发展新“冀”遇
[51 single chip microcomputer traffic light simulation]
31. Next arrangement
World Book Day: I'd like to recommend these books
Byte jump 2020 autumn recruitment programming question: quickly find your own ranking according to the job number
Free and open source charging pile Internet of things cloud platform
unity常见的问题(一)
Record a website for querying compatibility, string Replaceall() compatibility error
Free and open source intelligent charging pile SaaS cloud platform of Internet of things
HQL find the maximum value in a range
Install nngraph
Complete project data of UAV apriltag dynamic tracking landing based on openmv (LabVIEW + openmv + apriltag + punctual atom four axes)
Design of body fat detection system based on 51 single chip microcomputer (51 + OLED + hx711 + US100)
FFmpeg常用命令
SSM framework series - data source configuration day2-1