Node.js net模块

Node.js Net 模块提供了一些用于底层的网络通信的小工具,包含了创建服务器/客户端的方法。

var net = require('net');

var clientList = [];

//服务端
var netServer = net.createServer().on('connection', function(client) {
    //js可以自由给对象添加属性。ip地址默认是IPv6,客户端会启用一个随机的端口
    client.name = client.remoteAddress + '_' + client.remotePort;//ip地址是::ffff:127.0.0.1
    console.log('client.name = ' + client.name);
    console.log('net.isIP(client.remoteAddress) = ' + net.isIPv4(client.remoteAddress));//6, isIP判断地址是否是ip地址,如果是IPv4,则返回4;如果是IPv6,则返回6;如果是无效字符串则返回0。
    console.log('net.isIPv4(client.remoteAddress) = ' + net.isIPv4(client.remoteAddress));//false
    console.log('net.isIPv6(client.remoteAddress) = ' + net.isIPv6(client.remoteAddress));//true
    clientList.push(client);
    console.log('current client count = ' + clientList.length);
    //异步获取服务器当前活跃连接的数量,当socket发送给子进程后才有效。
    netServer.getConnections(function(err, count){
        if(err) {
            return console.error(err);  
        }
        console.log("net server getConnections = " + count);
    });
    client.on('data', function(chunk) {
        for(var i=0;i<clientList.length;i++) {
            if(client === clientList[i]) {
                //检查socket是否可写,如果不可写就直接销毁
                if(client.writable) {
                    client.write('\n'+client.name + " say : " + chunk+'\n');
                } else {
                    clientList.splice(clientList.indexOf(client), 1);
                    client.destroy();
                }
            }
        }
    }).on('end', function(){
        console.log('client quit, ' + client.name);
        clientList.splice(clientList.indexOf(client), 1);
        console.log('current client count = ' + clientList.length);
    }).on('error', function(e){
        console.error(e);
        //console.error(e.message);
    });
    client.write('Hi!\n');
    client.write('Hello World\n');
    client.write('Bye!\n');
    //服务端结束本次会话
    //client.end();
}).on('listening', function(){
    console.log('net server start listening...');
}).on('close', function(){
    console.log('net server is closed...');
}).on('error', function(e){
    console.log(e.message)
}).listen(8080);

//客户端
net.connect({host:'127.0.0.1', port:'8080'}, function(){
    console.log('客户端已连接上服务器');
}).on('data', function(chunk){
    //收到的数据默认是Buffer类型的,要使用toString()转化。但如果使用'+'和string连接,则会因为操作符被强制转化为string
    //console.log(chunk.toString());
    console.log('receivedData = ' + chunk);
}).on('end', function(){
    console.log('客户端已断开连接')
});

Telnet 也可以作为 “net模块” 的客户端。

telnet 127.0.0.1 8080

这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值