当前位置:网站首页>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
边栏推荐
- Mysql8 installation
- The accuracy and speed are perfectly balanced, and the latest image segmentation SOTA model is released!!!
- Proteus 8.10 installation problem (personal test is stable and does not flash back!)
- Date time type in database
- CVPR 2022&NTIRE 2022|首个用于高光谱图像重建的 Transformer
- unity常见的问题(一)
- After the data of El table is updated, the data in the page is not updated this$ Forceupdate() has no effect
- 梳理網絡IP代理的幾大用途
- Wonderful review | the sixth issue of "source" - open source economy and industrial investment
- Translation of multi modal visual tracking: review and empirical comparison
猜你喜欢
Record some NPM related problems (messy records)
Record the problems encountered in using v-print
Important knowledge of network layer (interview, reexamination, term end)
[untitled] PID control TT encoder motor
8 websites that should be known for product development to enhance work experience
31. 下一个排列
PC starts multiple wechat at one time
jmeter操作redis
There is no need to crack the markdown editing tool typora
Process virtual address space partition
随机推荐
SSM框架系列——注解开发day2-2
Byte jump 2020 autumn recruitment programming question: quickly find your own ranking according to the job number
V-model binding value in El select, data echo only displays value, not label
R语言中dcast 和 melt的使用 简单易懂
拥抱机器视觉新蓝海,冀为好望开启数字经济发展新“冀”遇
Byte warehouse intern interview SQL questions
Learning materials
JMeter operation redis
在线计算过往日期天数,计算活了多少天
The El table horizontal scroll bar is fixed at the bottom of the visual window
Important knowledge of network layer (interview, reexamination, term end)
three. JS text ambiguity problem
Kernel error: no rule to make target 'Debian / canonical certs pem‘, needed by ‘certs/x509_ certificate_ list‘
mysql8安装
MySQL —— 16、索引的数据结构
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
31. 下一个排列
leetcode-791. 自定义字符串排序
Record some NPM related problems (messy records)
(个人)最近项目开发后存在的系统漏洞整理