Home  >  Article  >  Web Front-end  >  Detailed explanation of nodeJS TCP module net instance

Detailed explanation of nodeJS TCP module net instance

零下一度
零下一度Original
2017-06-26 11:51:021726browse

Previous words

TCP services are very common in network applications. Currently, most applications are built based on TCP. The net module provides an asynchronous network wrapper for TCP network programming, which contains methods for creating servers and clients. This article will introduce the net module in nodeJS in detail

IP test

[net.isIP(input)]

Test whether the input is an IP address . Returns 0 if the string is invalid. Returns 4 in case of IPV4, returns 6 in case of IPV6

var net = require('net');
console.log(net.isIP('1.1.1.1'));//4console.log(net.isIP('1.1'));//0console.log(net.isIP('AD80::ABAA:0000:00C2:0002'));//6

【net.isIPv4(input)】

If the input address is IPV4, return true, otherwise return false

var net = require('net');
console.log(net.isIPv4('1.1.1.1'));//trueconsole.log(net.isIPv4('1.1'));//false

【net.isIPv6(input)】

If the input address is IPV6, return true, otherwise return false

var net = require('net');
console.log(net.isIPv6('1.1.1.1'));//trueconsole.log(net.isIPv6('AD80::ABAA:0000:00C2:0002'));//true

Server

[net.createServer([options][, connectionListener])】

Create a TCP server with the following parameters

options
    allowHalfOpen: false(默认),如果为true,当另一端socket发送FIN包时socket不会自动发送FIN包。socket变为不可读但可写(半关闭)
    pauseOnConnect: false(默认),如果为true,当连接到来的时候相关联的socket将会暂停。它允许在初始进程不读取数据情况下,让连接在进程间传递。调用resume()从暂停的socket里读取数据
connectionListener 自动给 'connection' 事件创建监听器
var server = net.createServer(function() {

});

【server.listen(port[, host][, backlog][, callback])】

Start accepting the specified port The connection between port and host. If host is omitted, the server will accept direct connections from any IPv4 address (INADDR_ANY). If the port is 0, a random port

will be allocated. The backlog is the maximum length of the connection waiting queue. The actual length is set by the operating system through sysctl, such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511

The 'listening' event will be triggered when the server is bound. The last parameter callback will be used as a listener for the 'listening' event. Some users will encounter an EADDRINUSE error, which indicates that another server is already running on the requested port. The way to handle this situation is to wait for a while and try again

server.listen(6000);
[server.close([callback])]

The server stops receiving new connections and keeps Existing connection. When all connections are completed the server will be closed and the 'close' event will be triggered. You can pass a callback function to listen for the 'close' event. If present, the callback function will be called with the error (if any) as the only parameter

[server.address()]

The operating system returns the bound address, protocol family name and server port. Very useful when finding which port has been bound by the system

[Note] Do not call server.address() before the 'listening' event is triggered

server.listen(function() {//{ address: '::', family: 'IPv6', port: 53806 }    console.log(server.address());
});
【 server.maxConnections】

After setting this option, new connections will be rejected when the number of server connections exceeds the number

Once the socket has been sent to the child process using the child_process.fork() method, it is not recommended. Use this option

[server.getConnections(callback)]

to asynchronously obtain the number of currently active connections on the server. It is only valid when the socket is sent to the child process;

The callback function has 2 parameters err and count

server.getConnections(function(err,count){
    console.log(count);//0})
[Event listening]

When the server Calling server.listen after binding will trigger

【Event connection】

{Socket object} 连接对象
Will be triggered when a new connection is created. The socket is an instance of net.Socket

[Event close]

Will be triggered when the server is closed

[Note] If there are connections, this event will not be triggered until all connections are connected Close

【Event error】

Triggered when an error occurs

Client

[net.connect(options[, connectionListener ])】

【net.createConnection(options[, connectionListener])】

The alias of connect() is the createConnection() method

This method returns a new ' net.Socket' and connect to the specified address and port. When the socket is established, the 'connect' event will be triggered. Has the same method as 'net.Socket'

For TCP sockets, the parameter options are as follows

port: 客户端连接到 Port 的端口(必须)
host: 客户端要连接到得主机。默认 'localhost'localAddress: 网络连接绑定的本地接口
localPort: 网络连接绑定的本地端口
family : IP 栈版本。默认 4
For local domain sockets, the parameter options are as follows

path: 客户端连接到得路径(必须)
var client = net.connect({port: 5000}, function() {});

Socket

【new net.Socket([options])】

Construct a new socket object

The options object has the following default values:

{ fd: null
  allowHalfOpen: false,
  readable: false,
  writable: false}

  参数fd允许指定一个存在的文件描述符。将readable和(或)writable设为true,允许在这个socket上读或写(仅在参数fd有效时)

【socket.connect(port[, host][, connectListener])】

【socket.connect(path[, connectListener])】

  使用传入的socket打开一个连接。如果指定了端口port和主机host,TCP socket将打开socket。如果忽略参数host,则默认为localhost。如果指定了path,socket将会被指定路径的unix socket 打开

  参数 connectListener 将会作为监听器添加到 'connect' 事件

【socket.write(data[, encoding][, callback])】

  在socket上发送数据。第二个参数指定了字符串的编码,默认是UTF8编码

  如果所有数据成功刷新到内核缓冲区,返回true。如果数据全部或部分在用户内存里,返回false。当缓冲区为空的时候会触发'drain'

  当数据最终被完整写入的的时候,可选的callback参数会被执行,但不一定会马上执行

【socket.end([data][, encoding])】

  半关闭socket。例如,它发送一个FIN包。可能服务器仍在发送数据。

  如果参数data不为空,等同于调用socket.write(data,encoding)后再调用socket.end()

【socket.destroy()】

  确保没有 I/O 活动在这个套接字上。只有在错误发生情况下才需要

【socket.pause()】

  暂停读取数据。就是说,不会再触发 data 事件。对于控制上传非常有用

【socket.resume()】

  调用 pause() 后想恢复读取数据

【socket.setTimeout(timeout[, callback])】

  socket 闲置时间超过 timeout 毫秒后 ,将 socket 设置为超时。触发空闲超时事件时,socket 将会收到 'timeout'事件,但是连接不会被断开。用户必须手动调用 end() 或 destroy() 这个socket。

  如果 timeout = 0, 那么现有的闲置超时会被禁用。可选的 callback 参数将会被添加成为 'timeout' 事件的一次性监听器

【socket.setNoDelay([noDelay])】

  禁用纳格(Nagle)算法。默认情况下 TCP 连接使用纳格算法,在发送前他们会缓冲数据。将 noDelay 设置为 true 将会在调用 socket.write() 时立即发送数据。noDelay 默认值为 true

【socket.setKeepAlive([enable][, initialDelay])】

  禁用/启用长连接功能,在发送第一个在闲置socket上的长连接probe之前,可选地设定初始延时。默认false

  设定initialDelay(毫秒),来设定收到的最后一个数据包和第一个长连接probe之间的延时。将 initialDelay 设为0,将会保留默认(或者之前)的值。默认值为0

【socket.address()】

  操作系统返回绑定的地址,协议族名和服务器端口。返回的对象有 3 个属性,比如{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

【socket.remoteAddress】

  远程的 IP 地址字符串

【socket.remoteFamily】

  远程IP协议族字符串

【socket.remotePort】

  远程端口,数字表示

【socket.localAddress】

  远程客户端正在连接的本地IP地址,字符串表示

【socket.localPort】

  本地端口地址,数字表示

【socket.bytesRead】

  接收的字节数

【socket.bytesWritten】

  发送的字节数

【事件lookup】

  在解析域名后,但在连接前,触发这个事件。对 UNIX sokcet 不适用

err {Error | Null} 错误对象
address {String} IP 地址。
family {String | Null} 地址类型

【事件connect】

  当成功建立 socket 连接时触发、

【事件data】

{Buffer object}

  当接收到数据时触发。参数 data 可以是 Buffer 或 String

  当 Socket 触发一个 'data' 事件时,如果没有监听器,数据将会丢失

【事件end】

  当 socket 另一端发送 FIN 包时,触发该事件

【事件timeout】

  当 socket 空闲超时时触发,仅是表明 socket 已经空闲。用户必须手动关闭连接

【事件drain】

  当写缓存为空得时候触发。可用来控制上传

【事件error】

  错误发生时触发

【事件close】

had_error {Boolean} 如果 socket 传输错误,为 true

  当 socket 完全关闭时触发。参数 had_error 是 boolean,它表示是否因为传输错误导致 socket 关闭

 

简易服务器

【服务器】

//server.jsvar net = require('net') ;var server = net.createServer(function(socket) { 
    socket.write("Hi!\n");
    socket.on("data", function(data) {
      console.log(data.toString());
    });
    socket.on("end", function() {
      console.log('有客户机下线了!!!');
    });
    socket.on('error', function() {
      console.log('发生意外错误!!!');
    });
}) ;
server.listen(8080) ;

【客户机】

//client.jsvar net = require('net') ;var client = net.connect({port: 8080},function(){
    client.name = '客户机1';
    client.write(client.name + ' 上线了!\n');
    client.end(client.name + ' 下线了!\n');
    client.on("data", function(data) {
        console.log(data.toString());
    });
});

 

简易聊天室

【服务器】

//chatServer.jsvar net = require('net');var i = 0;//保存客户机var clientList = [];var server = net.createServer(function(socket) {
    socket.name = '用户' + (++i);
    socket.write('【聊天室提示】欢迎' + socket.name + '\n');//更新客户机数组    clientList.push(socket); function showClients(){
        console.log('【当前在线用户】:');for(var i=0;i<clientList.length;i++) { 
            console.log(clientList[i].name);
        }        
    }
    showClients();
    socket.on("data", function(data) {//把当前连接的客户机的信息转发到其他客户机  for(var i=0;i<clientList.length;i++) { if(socket !== clientList[i]) {      
                clientList[i].write('【' + socket.name + '】:' + data);   
            }  
        }
    });
    socket.on("close", function() {//当前客户机下线时,将其从客户机数组中移除clientList.splice(clientList.indexOf(socket), 1);
        showClients();
    });
    socket.on('error', function(err) {
        console.log(socket.name + '退出');
    });
});
server.listen(8080) ;

【客户机】

//chatClient.jsvar net = require('net');
process.stdin.resume();
process.stdin.setEncoding('utf8');var client = net.connect({port: 8080},function(){
    console.log('【本机提示】登录到聊天室');
    process.stdin.on('data',function(data){
        client.write(data);
    })
    client.on("data", function(data) {
        console.log(data.toString());
    });
    client.on('end', function() {
        console.log('【本机提示】退出聊天室');
        process.exit();
    });
    client.on('error', function() {
        console.log('【本机提示】聊天室异常');
        process.exit();
    });
});

 

The above is the detailed content of Detailed explanation of nodeJS TCP module net instance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn