当前位置:网站首页>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
边栏推荐
- CMSIS cm3 source code annotation
- nodeJs + websocket 循环小案例
- 进程虚拟地址空间区域划分
- JMeter operation redis
- V-model binding value in El select, data echo only displays value, not label
- Utils of various date conversion
- Design and manufacture of 51 single chip microcomputer solar charging treasure with low voltage alarm (complete code data)
- Record a website for querying compatibility, string Replaceall() compatibility error
- Go iris framework implements multi service Demo: start (listen to port 8084) service 2 through the interface in service 1 (listen to port 8083)
- SSM framework series - data source configuration day2-1
猜你喜欢
jmeter操作redis
Softbank vision fund entered the Web3 security industry and led a new round of investment of US $60 million in certik
[untitled] make a 0-99 counter, P1 7 connected to key, P2 connected to nixie tube section, common anode nixie tube, P3 0,P3. 1. Connect the nixie tube bit code. Each time you press the key, the nixie
SSM framework series - data source configuration day2-1
Design of STM32 multi-channel temperature measurement wireless transmission alarm system (industrial timing temperature measurement / engine room temperature timing detection, etc.)
[Blue Bridge Cup] April 17 provincial competition brushing training (the first three questions)
Servlet监听器&过滤器介绍
If you were a golang interviewer, what questions would you ask?
将新增和编辑的数据同步更新到列表
Record a website for querying compatibility, string Replaceall() compatibility error
随机推荐
初鉴canvas,展示个小小的小案例
AUTOSAR from introduction to mastery 100 lectures (83) - bootloader self refresh
Design and manufacture of 51 single chip microcomputer solar charging treasure with low voltage alarm (complete code data)
CVPR 2022 & ntire 2022 | the first transformer for hyperspectral image reconstruction
「玩转Lighthouse」轻量应用服务器自建DNS解析服务器
melt reshape decast 长数据短数据 长短转化 数据清洗 行列转化
100 GIS practical application cases (34) - splicing 2020globeland30
async void 导致程序崩溃
filter()遍历Array异常友好
CGC: contractual graph clustering for community detection and tracking
[Technical Specification]: how to write technical documents?
Wonderful review | the sixth issue of "source" - open source economy and industrial investment
async void 導致程序崩潰
SQL exercise question 1
【微信小程序】flex布局使用记录
Go language array operation
mui 微信支付 排坑
如何实现点击一下物体播放一次动画
mui + hbuilder + h5api模拟弹出支付样式
Introduction to servlet listener & filter