node --- 创建一个Socket客户端连接到服务器

描述:

  • net.createrServer().listen(60300) 监听客户端访问
  • net.connect({ port: 60300 }) 访问服务器

服务器:

  • 一个很简单的监听文件改变的服务器
  • 每当监听的文件改变了,将信息通过json的格式传递给连接到的客户端 connection.write
// 01、net-watcher.js
'use strict'
const fs = require('fs');
const net = require('net');
const filename = process.argv[2];if (!filename) {throw Error('Error: No filename specified.');
}net.createServer(connection => {console.log('Subscriber connected.');connection.write(JSON.stringify({ type: 'watching', file: filename }) + '\n');const watcher =fs.watch(filename, () => connection.write(JSON.stringify({ type: 'changed', timestamp: Date.now() })));connection.on('close', () => {console.log('Subscriber disconnected.');watcher.close();});
}).listen(60300, () => console.log('Listening for subscriber...'));

客户端:

  • 使用 client = net.coonection({port: xxxx}) 连接到服务器.
  • 使用 client.on(‘data’) 来接收服务器传来的数据,并做相应的处理
// 02、net-watcher-json-client.js
'use strict';
const net = require('net');
const client = net.connect({ port: 60300 });
client.on('data', data => {const message = JSON.parse(data);if (message.type === 'watching') {console.log(`Now watching: ${message.file}`);} else if (message.type === 'changed') {const date = new Date(message.timestamp);console.log(` File changed: ${date} `);} else {console.log(`Unrecognized message type:${message.type}`);}
})

启动

  • 服务器
nodemon 01、net-watcher.js 1.txt

在这里插入图片描述

  • 客户端连接
nodemon 02、net-watcher-json-client.js

在这里插入图片描述

  • 每当改变1.txt, 服务器都会将信息传递给客户端这边.
    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/250711.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Laravel中的Blade模版

Blade模版简介 Blade模版的好处: 模版继承(template inheritance)视图片段(sections)部分指令: extend(‘xxx’)为子页面指定所继承的页面布局模版section(‘xxx’)为子页面提供所继承的页面中指定的部分…

三元表达式,列表解析和生成器表达式

三元表达式 在以前,在诸如比较两个数大小的时候,通常的写法都是下面的样子 if x > y:print("the max is x") else:print("the max is y") 三元表达式的语法为: True if expression else False 现在可以个体三元表达式…

Mysql 如何设置字段自动获取当前时间,附带添加字段和修改字段的例子

--添加CreateTime 设置默认时间 CURRENT_TIMESTAMP ALTER TABLE table_nameADD COLUMN CreateTime datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT 创建时间 ; --修改CreateTime 设置默认时间 CURRENT_TIMESTAMP ALTER TABLE table_nameMODIFY COLUMN CreateTime datetim…

css --- 圣杯布局

圣杯布局 左右固定宽度,中间自适应div:nth-child(1) section {display: flex;width: 60%;height: 150px;background-color: pink;margin: 0 auto; }section div:nth-child(1) {width: 100px;height: 150px;background-color: red; }section div:nth-child(2) {flex: 1;backgr…

FZU OJ:2230 翻翻棋

Problem 2230 翻翻棋Accept: 872 Submit: 2132Time Limit: 1000 mSec Memory Limit : 32768 KBProblem Description象棋翻翻棋(暗棋)中双方在4*8的格子中交战,有时候最后会只剩下帅和将。根据暗棋的规则,棋子只能上下左右移…

关于字符串比较时候出现的空指针问题的坑

比如说:String Tname driver.getTrueName(); 这个变量是从driver对象中取出的,但是你不知道这个值是空值null; 这个时候如果你这么写:Tname.equals("张三") 这个时候就会报空指针异常的 修改&#xff1a…

PHP 实现快速排序

首先了解快速排序的原理: 1、先取一个基值,用于每次的标准定位。 2、遍历数组,将大于基值的放到右边数组,小于的放到左边数组 3、将每次的左右数组和基值一起合并 代码实现: //快速排序 function quick_sort($arr…

css --- flex:n的解析

起步 效果如下: 在父元素中,将3个盒子平均分成了3等份代码如下: p span {flex: 1;background-color: lightcoral; }p span:nth-child(even) {border-right: 1px solid black;border-left: 1px solid black; }假设有3个子元素flex:1 的意思是,将剩余的宽度平均分成3份,然后该元…

1070: [SCOI2007]修车

/*一开始以为是个贪心 发现自己太naive了将每个技术工人拆成n个点,一共拆n*m个,第i个表示倒数第i次修车。 让每辆车向拆出来的点连边,费用为tmp[i][j]*k,i是技工,j是车,k是拆出来的第几个点, 这…

PHP 实现冒泡排序

PHP 实现冒泡排序 直接上代码 //冒泡排序 function bubble_sort($array){$count count($array);if ($count<0) {return false;}for ($i0; $i <$count ; $i) { for ($j0; $j <$count-$i-1 ; $j) { if ($array[$j]>$array[$j1]) {$tmp $array[$j1];$array[$j1]$a…

node --- 后端使用bcrypt对密码进行加密处理

密码的处理 加密处理在线调试: http://www.atool9.com/hash.phpbcrypt: 加密工具安装 && 使用 npm install --save bcryptconst bcrypt require(bcrypt); const SALT_WORK_FACTOR 10;const UserSchema new Schema({UserId: {type: ObjectId},password: String })U…

统一建模语言UML

目录 1. UML定义2. UML结构2.1 视图&#xff08;View&#xff09;2.2 图&#xff08;Diagram&#xff09;2.3 模型元素&#xff08;Model element&#xff09;2.4 通用机制&#xff08;General mechanism&#xff09;3. 类图3.1 类与类图3.2 类之间的关系3.2.1 关联关系3.2.2 聚…

SpringCloud系列七:使用Ribbon实现客户端侧负载均衡

1. 回顾 在前面&#xff0c;已经实现了微服务的注册与发现。启动各个微服务时&#xff0c;Eureka Client会把自己的网络信息注册到Eureka Server上。 但是&#xff0c;在生成环境中&#xff0c;各个微服务都会部署多个实例&#xff0c;因此还行继续进行优化。 2. Ribbon简介 Ri…

node --- 使用koa-router,让后端模块化

使用Koa-router进行路由管理 npm install --save koa-router const Router require(koa-router); let router new Router(); router.get(/, async (ctx)>{ctx.body 用户操作首页 })路由模块化 在appApi下面创建需要模块化的文件如:home.js、user.js const Router re…

PHP 实现桶排序

PHP 实现桶排序 <?phpfunction Bucket_sort($array){//初始化桶大小$min min($array);$max max($array);$book array_fill($min, $max-$min1, 0);//将要进行的数据进行计数foreach ($array as $key) {$book[$key];// echo $book[$key];}//返回数据$resArr array();for…

springboot ajax返回html

因为拦截器 或者是 shiro 拦截登陆接口 转载于:https://www.cnblogs.com/xdcr/p/9638569.html

【小试牛刀】短信验证码(随机数)的生成实现

短信验证码&#xff0c;相信在生活中大家是几乎天天能够遇到。但你知道它是怎样生成的吗&#xff1f;其实它就是若干位数的随机数组合而成。下面附上一小段程序&#xff0c;供大家一起学习交流。package com.fhcq.util;import org.apache.commons.lang3.RandomStringUtils;publ…

node --- 后端使用body-parse解析Post请求,前端使用axios发送Post请求

使用body-parser解析post请求 安装service/index.js npm install --save koa-bodyparser导入 const Koa require(koa); const app new Koa(); const bodyParser require(koa-bodyparser); app.use(bodyParser)准备请求的url全局配置src/serviceAPI.config.js const LOCA…

PHP 实现二分查找

PHP 实现二分查找 原理&#xff1a; 首先&#xff0c;假设数组中元素是按升序排列&#xff0c;将表中间位置记录的关键字与查找关键字比较&#xff0c;如果两者相等&#xff0c;则查找成功&#xff1b;否则利用中间位置记录将数组分成前、后两个子数组&#xff0c;如果中间位…

python基础:条件循环字符串

while True:a int(input(摄氏度转换为华氏温度请按1\n华氏温度转化为摄氏温度请按2\n))if a 1:celsius float(input(输入摄氏温度&#xff1a;))fahreaheit (celsius 1.8) 32 # f c9/532print({:.2f}摄氏温度转为华氏温度为{:.2f}.format(celsius, fahreaheit))elif a …