Home>Article>Web Front-end> Detailed explanation of TCP/IP data communication in Node.js

Detailed explanation of TCP/IP data communication in Node.js

小云云
小云云 Original
2018-01-25 11:23:23 1931browse

This article mainly brings you an article on TCP/IP data communication for Node.js learning (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

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

Provides a net module dedicated to realizing communication between the TCP server and the TCP client

1.1 Create a 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){ //回调函数代码 }

The parameter value is the socket port object that the TCP server listens to. The createServer method returns the created TCP server

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端口对象,文件描述符)

Here is an example to 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 can get the following results:

Use telnet to access the corresponding server:

telnet localhost 8431

The results that will appear are as follows:

socket port object example:

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

Establish TCP client example:

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, the 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服务器被关闭。'); })

In Node.js, the following method can be used to continuously send detection packets to the client or server to determine the connection status;

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

Related recommendations:

Node.js creates Web and TCP servers

A brief analysis of the three-way handshake four of TCP transmission Wave strategy

What is the difference between TCP/IP and UDP

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