当前位置:网站首页>nodeJs + websocket 循环小案例
nodeJs + websocket 循环小案例
2022-04-23 13:04:00 【孤身不觉晚】
开局一个项目,咱们先给项目装一个nodeJs的模块,叫nodejs-websocket ,
npm install nodejs-websocket
服务端
var ws = require("nodejs-websocket")
var index = 0;
let IndexNum;
var server = ws.createServer(function(conn) {
console.log("New connection")
//conn.on("***",function(){}) 绑定事件(***)及事件的处理程序
conn.on("text", function(str) {
//事件:“ text(str)”收到文本时发出。str是一个字符串
console.log(str);
if(str == 1 ){
IndexNum = setInterval(()=>{
let mes = {
};
mes.index = index++;
mes.number = parseInt (Math.random()*100);
//JSON.stringify(mes)系列化对象,把对象的类型转换为字符串类型
conn.sendText(JSON.stringify(mes));//将给定的字符串发送到前端
},1000);
}else{
conn.sendText('erro');
}
})
conn.on("close", function(code) {
//开始关闭握手(发送关闭帧)
console.log("关闭",code);
clearInterval(IndexNum);
})
conn.on("error", function(err) {
//发生错误时发出。如果握手无效,也会发出响应。
console.log(err);
})
}).listen(3000);//服务器监听端口3000
console.log("websocket server running on port: 3000");
客户端
<body>
<button onclick="begin()">开始</button>
<button onclick="stop()">停止</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("连接成功"); } websocket.onclose = function() {
console.log("websocket close"); } function begin(){
websocket.send(1); } function stop(){
websocket.close(); } // 只接收字符串参数,所以在服务端相传对象过来可以用JSON先转换成字符串,然后在这边转成对象 websocket.onmessage = function(e) {
let data = JSON.parse(e.data); let text = `<li>第${
data.index}次,数字是${
data.number};</li>` box.innerHTML += text; } </script>
</body>
版权声明
本文为[孤身不觉晚]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40043424/article/details/105240423
边栏推荐
- Get the punch in record of nailing attendance machine
- Byte jump 2020 autumn recruitment programming question: quickly find your own ranking according to the job number
- Golang implements a five insurance and one gold calculator with web interface
- The quill editor image zooms, multiple rich text boxes are used on one page, and the quill editor upload image address is the server address
- XinChaCha Trust SSL Organization Validated
- SSL certificate refund instructions
- 世界读书日:我想推荐这几本书
- Homomorphic encryption technology learning
- 梳理網絡IP代理的幾大用途
- 内核错误: No rule to make target ‘debian/canonical-certs.pem‘, needed by ‘certs/x509_certificate_list‘
猜你喜欢
[Blue Bridge Cup] April 17 provincial competition brushing training (the first three questions)
CGC: contractual graph clustering for community detection and tracking
100 GIS practical application cases (52) - how to keep the number of rows and columns consistent and aligned when cutting grids with grids in ArcGIS?
Calculate the past date and days online, and calculate the number of live days
Record Alibaba cloud server mining program processing
Important knowledge of network layer (interview, reexamination, term end)
Record some NPM related problems (messy records)
Trier les principales utilisations de l'Agent IP réseau
98. Error s.e.errormvcautoconfiguration $staticview reported by freemaker framework: cannot render error page for request
SSM framework series - data source configuration day2-1
随机推荐
Summary of JVM knowledge points - continuously updated
Servlet监听器&过滤器介绍
The continuous construction of the Internet industry platform is not only able to collect traffic
4. DRF permission & access frequency & filtering & sorting
教你快速开发一个 狼人杀微信小程序(附源码)
V-model binding value in El select, data echo only displays value, not label
PC starts multiple wechat at one time
Temperature and humidity monitoring + timing alarm system based on 51 single chip microcomputer (C51 source code)
Design and manufacture of 51 single chip microcomputer solar charging treasure with low voltage alarm (complete code data)
100 GIS practical application cases (51) - a method for calculating the hourly spatial average of NC files according to the specified range in ArcGIS
(personal) sorting out system vulnerabilities after recent project development
leetcode-791. Custom string sorting
22. Bracket generation
CVPR 2022&NTIRE 2022|首个用于高光谱图像重建的 Transformer
STM32 is connected to the motor drive, the DuPont line supplies power, and then the back burning problem
HQL statement tuning
Teach you to quickly develop a werewolf killing wechat applet (with source code)
Baserecyclerviewadapterhelper realizes pull-down refresh and pull-up loading
Important knowledge of transport layer (interview, retest, final)
Huawei cloud MVP email