当前位置:网站首页>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
边栏推荐
- Pytorch: a pit about the implementation of gradreverselayer
- 教你快速开发一个 狼人杀微信小程序(附源码)
- STM32 is connected to the motor drive, the DuPont line supplies power, and then the back burning problem
- Deploying MySQL in cloud native kubesphere
- 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?
- leetcode-791. Custom string sorting
- The El table horizontal scroll bar is fixed at the bottom of the visual window
- Recovering data with MySQL binlog
- 21 days learning mongodb notes
- 将新增和编辑的数据同步更新到列表
猜你喜欢

Navicat远程连接数据库 出现 1130- Host xxx is not allowed to connect to this MySQL server错误

Record the problems encountered in using v-print

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

拥抱机器视觉新蓝海,冀为好望开启数字经济发展新“冀”遇

melt reshape decast 长数据短数据 长短转化 数据清洗 行列转化

SSM framework series - annotation development day2-2

100 GIS practical application cases (53) - making three-dimensional image map as the base map of urban spatial pattern analysis
![[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](/img/d1/b0ec21419db0cd3641f5fae8458c50.png)
[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

How to click an object to play an animation

World Book Day: I'd like to recommend these books
随机推荐
JMeter operation redis
Object. The disorder of key value array after keys
Free and open source charging pile Internet of things cloud platform
Process virtual address space partition
Introduction to servlet listener & filter
4.22学习记录(你一天只做了水题是吗)
Importerror after tensorflow installation: DLL load failed: the specified module cannot be found, and the domestic installation is slow
mysql支持ip访问
JDBC connection pool
4.22 study record (you only did water problems in one day, didn't you)
decast id.var measure.var数据拆分与合并
CGC: contractual graph clustering for community detection and tracking
Pyqt5 store opencv pictures into the built-in sqllite database and query
The El table horizontal scroll bar is fixed at the bottom of the visual window
STM32 is connected to the motor drive, the DuPont line supplies power, and then the back burning problem
内核错误: No rule to make target ‘debian/canonical-certs.pem‘, needed by ‘certs/x509_certificate_list‘
Design of body fat detection system based on 51 single chip microcomputer (51 + OLED + hx711 + US100)
世界读书日:我想推荐这几本书
There is no need to crack the markdown editing tool typora
SSM framework series - data source configuration day2-1