Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Node.js for TCP Network Communication

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you how to use Node.js for TCP network communication, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Abstract: network is the basis of communication and interconnection. Node.js provides net, http, dgram and other modules, which are used to realize the communication of TCP, HTTP and UDP respectively.

1. Build a TCP server

1.1.Use Node.js to create a TCP server

To create a TCP server using Node.js, first call require ('net') to load the net module, and then call the createServer method of the net module to easily create a TCP server in the following syntax format:

Net.createServer ([options] [, connectionListener]) options is an object parameter value with two properties of Boolean type allowHalfOpen and pauseOnConnect. The default for both properties is that false;connectionListener is a callback function when the client establishes a connection with the server, which takes the socket port object as an argument.

1.2. Listen for client connections

You can start listening for client connections by using the listen method of the TCP server. The syntax format is as follows:

Server.listen (port [, host] [, backlog] [, callback]); port: for the port number to be listened on, a port number is randomly assigned when the parameter value is 0; host: server address; backlog: maximum length of connection waiting queue; callback: callback function.

The following code creates a TCP server and listens to port 8001:

/ / introduce net module const net = require ('net'); / / create TCP server const server = net.createServer (function (socket) {console.log (' new client access');}); / / set listening port server.listen (8001, function () {console.log ('service is listening.') });

When you run this code, you can see the callback function that executes the listen method on the console, as shown in the figure:

You can use the appropriate TCP client or debugging tool to connect to the TCP server that has been created. For example, to use Windows's Telnet, you can connect with the following command:

Telnet localhost 8001

After a successful connection, you can see that the console prints the words "New client access", indicating that the callback function of the createServer method has been executed, indicating that you have successfully connected to the created TCP server.

The server.listen () method actually triggers the listening event under server, so you can also listen to the listening event manually as follows:

/ / set the listening port server.listen (8001); / / set the callback function server.on ('listening', function () {console.log ("the service is listening.") });

In addition to the listening event, the TCP server supports the following events:

Connection: triggered when a new link is created, and the callback function takes the socket connection object as the argument. Triggered when the close:TCP server is shut down, and the callback function takes no arguments. Triggered when an error occurs on the error:TCP server, and the callback function takes an error object as the argument.

The following code creates a TCP server through the net.Server class, adding the above events:

/ / introduce net module const net = require ('net'); / / instantiate a server object const server = new net.Server (); / / listen for connection event server.on (' connection', function (socket) {console.log ('new client access');}); / / set listening port server.listen (8001) / / set the callback function server.on ('listening', function () {console.log (' service is listening.') ;}); / / set the callback function server.on ('close', function () {console.log (' service has been shut down');}); / / set the callback function server.on in case of error ('error', function (err) {console.log (' service running exception', err);})

1.3. View the address that the server is listening to

When you create a TCP server, you can use the server.address () method to view the address that the TCP server is listening to and return a JSON object. Because this method returns the address information that the TCP server is listening to, it should be called when the server.listen () method is called or the callback function in the event listening is bound. The properties of this object are:

The port number that the port:TCP server listens to; family: indicates whether the address that the TCP server listens to is IPv6 or the address that IPv4;address:TCP server listens to.

The code is as follows:

/ / introduce net module const net = require ('net'); / / create TCP server const server = net.createServer (function (socket) {console.log (' new client access');}); / / set listening port server.listen (8001); / / set callback function server.on ('listening', function () {/ / get address information let address = server.address () / / get address details console.log ("the port that the server listens to is" + address.port); console.log ("the address that the server listens to is:" + address.address); console.log ("the address type that the server listens to is:" + address.family);})

The running result is shown in the figure:

1.4. Number of clients connected to the server

After you create a TCP server, you can get the number of clients connected to the TCP server through the server.getConnections () method. This method is asynchronous, and the callback function takes two parameters:

The first parameter is the error object. The second parameter is the number of clients connected to the TCP server.

In addition to getting the number of connections, you can also set the maximum number of connections for this TCP server by setting the maxConnections property of the TCP server. When the number of connections exceeds the maximum number of connections, the server will reject new connections. The following code sets the maximum number of connections for this TCP server to 3.

/ / introduce net module const net = require ('net'); / / create TCP server const server = net.createServer (function (socket) {console.log (' new client access'); / / set maximum number of connections server.maxConnections = 3; server.getConnections (function (err, count) {console.log ("number of clients currently connected is" + count);});}) / / set the listening port server.listen (8001, function () {console.log ("the service is listening.") });

Run this code and try to connect with multiple clients. You can find that when the number of client connections exceeds 3, the new client cannot connect to the server, as shown in the figure:

1.5. Get the data sent by the client

The callback function parameter of the createServer method is a net.Socket object (the port object that the server listens to), which also has an address () method that gets the address bound to the TCP server, and also returns an object with port, family, and address properties. The stream data sent by the client can be obtained through the socket object. Each time the data is received, the data event is triggered. By listening to this event, the data sent by the client can be obtained in the callback function. The code is as follows:

/ / introduce net module const net = require ('net'); / / create TCP server const server = net.createServer (function (socket) {/ / listen for data event socket.on ("data", function (data) {/ / print data console.log ("received data: + data.toString ();});}) / / set the listening port server.listen (8001, function () {console.log ("the service is listening.") });

The test results are as follows:

In addition to data events, socket objects also have connect, end, error, timeout, and so on.

1.6. Send data to the client

Calling socket.write () causes the TCP server to send data, which has only one required parameter, which is the data to be sent; the second parameter is an optional encoding format. At the same time, you can set a callback function for this method. When a user connects to the TCP server, the data will be sent to the client as follows:

/ / introduce net module const net = require ('net'); / / create TCP server const server = net.createServer (function (socket) {/ / set message content const message = "Hello Client."; / / send data socket.write (message, function () {const writeSize = socket.bytesWritten; console.log ("data sent successfully, data length is:" + writeSize);}) / / listen to the data event socket.on ("data", function (data) {const readSize = socket.bytesRead; / / print data console.log ("received data is:" + data.toString (), " The length of the data received is: "+ readSize);});}); / / set the listening port server.listen (8001, function () {console.log (" Service is listening. ") });

The test results are as follows:

The bytesWritten and bytesRead properties of the socket object are also used in the above code, which represent the number of bytes of data sent and received, respectively. In addition to the above two properties, the socket object has the following properties:

Socket.localPort: local port address; socket.localAddress: local IP address; socket.remotePort: process port address; socket.remoteFamily: process IP protocol family; socket.remoteAddress: process IP address. 2. Build TCP client

Node.js also uses the net (Network) module when creating a TCP client.

2.1.Create a TCP client using Node.js

To create a TCP client using Node.js, first call require ('net') to load the net module. To create a TCP client, you only need to create a socket object that connects to the TCP client:

/ / introduce net module const net = require ('net'); / / create TCP client const client = new net.Socket ()

When you create a socket object, you can pass in a json object. This object has the following properties:

Fd: specify a file descriptor that exists. The default value is null;readable: whether to read on this socket. The default value is false;writeable: whether to write on this socket. The default value is false;allowHalfOpen: when this attribute is false, when the TCP server receives a FIN packet sent by the client, it will send back a FIN packet; when this attribute is true, the TCP server will not send back a FIN packet when it receives a FIN packet sent by the client.

2.2. Connect to the TCP server

After creating a socket object, you can connect to a TCP server by calling the connect () method of the socket object, as follows:

/ / introduce net module const net = require ('net'); / / create TCP client const client = new net.Socket (); / / set connected server client.connect (8001,' 127.0.0.1 server, function () {console.log ("connection to server");})

The successful connection is shown in the following figure:

Get the data sent from the TCP server

Socket objects include data, error, close, end and other events, because you can get the data sent from the TCP server by listening for data events, as shown below:

/ / introduce net module const net = require ('net'); / / create TCP client const client = new net.Socket (); / / set connected server client.connect (8001,' 127.0.0.1 server, function () {console.log ("connection to server");}) / / listen for data event client.on ("data", function (data) {/ / print data console.log ("received data is:" + data.toString ());})

Start the TCP server first, and then run the client above. You can find that the data from the server has been output from the command line, indicating that the communication between the server and the client has been realized:

2.4. send data to the TCP server

Because the TCP client is a socket object, you can use the following code to send data to the TCP server:

/ / introduce net module const net = require ('net'); / / create TCP client const client = new net.Socket (); / / set the connected server client.connect (8001,' 127.0.0.1 server, function () {console.log ("connect to the server successfully"); / / send data client.write ("Hello Server.");}) to the server / / listen to data event client.on ("data", function (data) {/ / print data console.log ("received data is: + data.toString ());}); / / listen to end event client.on (" end ", function () {console.log (" end of client sending data ")})

Client console output:

Server console output:

On how to use Node.js for TCP network communication is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report