Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Principle of Node – TCP service in Network Services – TCP introduction

Last article we said that Node can be very convenient to build a network server, Node built-in template NET, Dgram, HTTP, HTTPS respectively handle TCP, UDP, HTTP, HTTPS, and introduced the basic knowledge of TCP. This article will look at how to build a TCP service with Node

TCP Service Practices

const net = require('net');
const server = net.createServer((socket) = > {
    socket.on('data'.(data) = > {
        socket.write('data hello');
    })
    socket.on('end'.(data) = > {
        socket.write('end');
    })
    socket.write('tcp hello');
})
server.listen(8082.() = > {
    console.log('tcp server bound');
})
console.log("Hello World");
Copy the code

We create a TCP server using net.createserver (Listener), which is a listener for connection events and can also listen in the following way

const net = require('net');
const server = net.createServer();
server.on('connection'.function (socket) { 
    // New connection
}); 
server.listen(8082);
Copy the code

We can use the Telnet tool as a client to talk to the simple server we just created

$ telnet 127.0. 01. 8082
Copy the code

UDP service

UDP, also known as user Data Packet protocol, is at the same transport layer as TCP. The biggest difference between TCP and UDP is that UDP is not connection-oriented. All sessions in TCP are based on connections. If a client wants to communicate with another TCP service, it needs to create a socket to complete the connection. But in UDP, a socket can communicate with multiple UDP services.

UDP is a simple and unreliable connection service. Packet loss may occur when the network environment is poor. However, UDP does not require connection, consumes low resources, and can be used in audio and video transmission scenarios where loss of one or two packets is not a major impact.

UDP is widely used, and DNS is based on UDP.

The next article will cover UDP in action. Please feel free to like and comment