小言_互联网的博客

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

231人阅读  评论(0)

描述:

  • 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, 服务器都会将信息传递给客户端这边.

转载:https://blog.csdn.net/piano9425/article/details/101027846
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场