Home  >  Article  >  Web Front-end  >  Node.js learning TCP/IP data communication

Node.js learning TCP/IP data communication

一个新手
一个新手Original
2017-10-12 09:54:301724browse

Node.js Learning TCP/IP Data Communication

1. Use the net module to implement TCP-based data communication

Provides a net module dedicated to implementing TCP servers and TCP clients Communication between terminals

1.1 Create TCP server

Use the net module to create a TCP server in Node.js

var server = net.createServer([options],[connectionListener])
//options:false当TCP服务器接收到客户端发送的一个FIN包时将会回发一个FIN包
           true当TCP服务器接收到客户端发送的一个FIN包时将不会回发FIN包,这使得TCP服务器可以继续向客户端发送数据,但不会继续接收客户端发送的数据。来发者必须调用end方法来关闭socket连接。默认为false
connectionListener:指定当客户端与服务器端简历连接时所要调用的回调函数
function(socket){
    //回调函数代码
}
参数值为TCP服务器监听的socket端口对象

The createServer method returns the created TCP server
When When the client establishes a connection with the server, the connection event is triggered. You can use the following method to execute the callback function

server.on('connection',function(socket){
//回调函数代码
})

After creating the TCP server, use the listen method to notify the server to start monitoring the client connection

server.listen(port,[host],[backlog],[callback])
//port指定需要监听的端口号,
host:指定需要监听的IP地址或主机名,如果省略,服务器将监听来自于任何IPv4地址的客户端连接
backlog:指定位于等待队列中的客户端连接的最大数量
callback:无参回调函数

server.listen(path,[callback])
//server:代表一个使用unix端口的服务器
path:指定需要监听的路径,会触发listening事件,然后执行回调函数callback

server.listenting(handle,[callback])
//server 代表一个TCP服务器
handle:指定需要监听的socket句柄(该句柄可以为一个TCP服务器对象,socket端口对象,文件描述符)

Now For example, create a TCP server:

var net = require('net')
var server = net.createServer(function(socket){
    console.log('客户端与服务器连接已建立')
})
server.listen(8431,'localhost',function(){
    console.log('服务器端开始监听')
})

After running, you will get the following results:

Node.js learning TCP/IP data communication

Use telnet to access the corresponding server:

telnet localhost 8431

will The results that appear are as follows:

Node.js learning TCP/IP data communication

Example of socket port object:

var net = require('net')
var file = require('fs').createWriteStream('./message.txt');
var server = net.createServer(function(socket){
console.log('客户端与服务器连接已建立')
server.getConnections(function(err,count){
    console.log('当前存在%d个客户端连接。',count);
    server.maxConnections = 4;
    console.log('TCP服务器的最大连接数为%d',server.maxConnections);
    
})

// server.close(function(){
    // console.log('TCP服务器被关闭。');
// })
})
server.listen(8431,'localhost',function(){
console.log('服务器端开始监听')

})
server.on('connection',function(socket){
address = socket.address();
console.log('被监视的地址信息为%j',address);
socket.pipe(file);
socket.setEncoding('utf8');
socket.on('data',function(data){
    console.log(data.toString());
    console.log('已接受到%d字节数据。',socket.bytesRead);
});
socket.on('end',function(){
    file.end('再见')
    console.log('客户端连接被关闭。')
})

socket.pause();
setTimeout(function(){
    console.log('*************')
    socket.resume();
    socket.pipe(file,{end:false});
},30*1000);
// socket.pipe(file,{end:false});
// setTimeout(function(){
    // file.end('再见。');
    // socket.unpipe(file);
// },5000);
socket.setTimeout(10*1000);
socket.on('timeout',function(){
    console.log('客户端连接超时');
    socket.setTimeout(0);
})

})

1.2 Create TCP client

Example of creating TCP client:

var net = require("net");
var client = new net.Socket();
client.setEncoding('utf8');
client.connect(8431,'localhost',function(){
console.log('已连接到服务器');
client.write('你好');
console.log('当前已发送%d字节',client.bytesWritten);
client.end('再见')
console.log('当前已发送%d字节',client.bytesWritten);
// setTimeout(function(){
    // client.end('再见');        
// },10*1000)

});
client.on('data',function(data){
//console.log('已接收服务器端发送的数据: '+data);
console.log('已接收服务器端发送的数据');
})
client.on('error',function(err){
console.log('与服务器连接或通信的过程中发生了一个错误,错误编码为%s',err.code);
client.destroy();
})

At the same time, a corresponding server needs to be established:

var net = require('net');
var fs = require('fs');
var server = net.createServer();
server.on('connection',function(socket){
console.log('客户端与服务器端连接已建立');
socket.setEncoding('utf8');
var readStream = fs.createReadStream('./server.js');
readStream.on('data',function(data){
    var flag = socket.write(data);
    console.log('write方法的返回值为:'+flag);
    console.log('缓存队列中当前缓存了%d字符。',socket.bufferSize);
})
socket.on('data',function(data){
    console.log('已连接客户端发送的数据:'+data);
    socket.write('确认数据:'+data);
})
socket.on('error',function(err){
    console.log('客户端通信的过程中发生了一个错误,错误编码为%s',err.code);
    socket.destroy();
})
socket.on('end',function(){
    console.log('客户端连接被关闭。');
    server.unref();
})
socket.on('close',function(had_error){
    if(had_error){
        console.log('由于一个错误导致socket端口被关闭。');
        server.unref();
    }else{
        console.log('socket端口被正常关闭。');
    }
})
server.getConnections(function(err,count){
    if(count==2)
        server.close();
});
});

server.listen(8431,'localhost');
server.on('close',function(){
console.log('TCP服务器被关闭。');
})

Use the following method in Node.js to continuously send detection packets to the client or server to determine the connection status;

socket.setKeepAlive([enable],[initialDelay])
//enable:true:启用Keep-alive机制,不断向对方发送一个探测包,如果没有回应表示连接关闭
initialDelay:间隔时间(毫秒)

The above is the detailed content of Node.js learning TCP/IP data communication. 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