Co-creating author: Zhang Xiaoxu Gold excavation homepage: juejin.cn/user/852876…
network
TCP/IP network protocol
Before we talk about TCP/IP, let’s take a look at the OSI seven-tier model.
Layer 7: The application layer provides the interface for the operating system or network applications to access network services. Application layer protocols include HTTP, HTTPS, FTP, TELNET, SSH, SMTP, and POP3. Layer 6: The presentation layer converts data into content that is compatible with the receiver and suitable for transmission, such as data encryption, compression, format conversion, etc. Layer 5: The session layer is responsible for setting up and maintaining communication connections between network devices in data transmission. Manages session processes between hosts, and can also synchronize data by inserting checkpoints into the data. Layer 4: The transport layer adds the transport table header to the data to form a packet to complete the end-to-end data transmission. The transport header contains protocol information, such as TCP, UDP, etc. Layer 3: The network layer is responsible for addressing and routing packets between subnets, and can also achieve congestion control, Internet interconnection and other functions. The network layer protocols include IP and IPX. For example, routers are at this layer 2: the data link layer provides reliable transmission over unreliable physical media. The main functions are: physical address addressing, data encapsulation into frames, flow control, data verification, retransmission, etc. Switches, for example, are at layer 1: the physical layer that transmits data frames over the LAN and is responsible for the interworking between computer communications equipment and network media, including pins, voltages, cable specifications, hubs, network cards, host adaptors, and so on.
Some interview questions:
- At what level is HTML?
The application layer
- So what do we mean by this deal we keep talking about? What is the agreement?
In general terms, protocols define what each layer does and what each layer’s responsibilities are, similar to specifications and constraints.
- What is TCP/IP?
Some articles specifically refer to TCP and IP protocol, but most of the time mentioned TCP/IP protocol, can be understood as the protocol required for Internet communication, is a family of protocols, TCP, IP protocol as the core, including HTTP, SMTP, TELNET and other protocols.
- TCP/IP reference model?
The TCP/IP reference model is an abstract hierarchical model in which all the TCP/IP family of network protocols are grouped into four abstract “layers.”
Take a look at the image below
- What do we often say about packets?
A packet is a unit of packets at the network layer and above.
Each layer adds a header to the data to be sent. The header contains information related to the protocol of the layer. The actual content to be sent is called data.
This means that each packet consists of header + data.
For the lower layer, all the content sent by the upper layer is regarded as the data of the lower layer. For example:
Transport layer TCP packet: TCP packet header + data Network layer IP packet: IP packet header + (TCP packet header + data) Data Link Layer Ethernet packet: Ethernet packet header + (IP packet header + (TCP packet header + data))
- What does each layer do after receiving data besides adding headers?
User 1
- Transport layer: To ensure reliable data transmission, the TCP header needs to be added
- Network layer: After an IP packet is generated, the route or host that accepts the IP packet is determined by referring to the routing control table.
- Data link layer: The generated Ethernet packets are transmitted to the receiver through the physical layer
The user 2
- Data link layer: After receiving an Ethernet packet, the host finds the MAC address in the packet header and determines whether the packet is destined for the host. If not, the host dismisses the data.
If the packet is sent to itself, the data type is determined from the type in the header of the Ethernet packet and then transmitted to the corresponding module, such as IP.
- Network layer: Determines whether the IP address in the packet header matches its own IP address. If yes, the data is sent to the corresponding module based on the protocol type of the packet header, such as TCP
- Transport layer: In the TCP module, the checksum is first calculated to determine whether the data is corrupted. It then checks to see if the data is being received in sequence. Finally, check the port number to determine the specific application. Once the data has been received in its entirety, it is passed to the application identified by the port number.
To summarize a few addresses:
- At the data link layer, MAC addresses are used to identify different computers on the same link
- At the network layer are IP addresses that identify interconnected hosts and routers in a TCP/IP network
- At the transport layer are port numbers (program addresses) that identify different applications communicating on the same computer
- So we can identify a communication through these three addresses?
The answer is no.
We need to identify a communication by combining the following data:
- IP header: indicates the source IP address
- IP header: indicates the destination IP address
- Protocol number, TCP or UDP
- TCP header: indicates the source port number
- TCP header: indicates the target port number
- What’s the difference between what we call TCP/UDP? What is the appropriate scenario for each?
- UDP is connectionless, and TCP requires a three-way handshake to establish a connection
- UDP is packet oriented and has no congestion control. Therefore, it is fast and suitable for multimedia communication. For example, it supports one-to-one chat and multiple teams. Many-to-one, many-to-many. For example, the video interview at Niuke.com uses UDP
- TCP supports only one – to – one reliable transmission
So what’s the underlying protocol?
In fact, now common RTMP and HLS live, are based on TCP, hoping to provide a stable live environment.
- How does TCP provide reliability?
- Timeout resend. If the sent segment does not receive timely acknowledgement, it will resend.
- Check packets, that is, check header data sum.
- Reorder the disordered data
- Perform flow control to prevent buffer overflow
- Fast retransmission and fast recovery
- TCP truncates the data to a reasonable length
- How does TCP control congestion?
Congestion control is to prevent excessive data injection into the network, so that the network routers or links do not overload. The sender maintains a state variable called CWND (congestion Window). To prevent network congestion caused by CWND growth, a slow start threshold SSthRESH state variable should also be set. The use of ssthresh is as follows: When CWND < SSthRESH, use the slow start algorithm. That is the multiplication algorithm when CWND > SSthRESH, switch to congestion avoidance algorithm. That is the addition algorithm when CWND = SSthRESH, slow start and congestion avoidance algorithm arbitrary. When congestion occurs, set the heart threshold to the normal window size, set the window size to 1, and then perform the above steps again. When you get three consecutive retransmissions you need fast retransmissions and fast recovery, when you get three consecutive retransmissions the sender has to retransmit himself, and then the threshold is halved but it’s not a network jam, it’s just halved the window and the congestion avoidance algorithm is implemented.
- What is the process of establishing and disconnecting a TCP data transmission?
First handshake: Establishes a connection. The client sends a connection request packet with the SYN position as 1 and Sequence Number as x. Then, the client enters the SYN_SEND state and waits for confirmation from the server. Second handshake: When receiving the SYN packet segment from the client, the server needs to acknowledge this Acknowledgment by setting the Acknowledgment Number to X +1(Sequence Number+1). In addition, you also send SYN request information with the SYN position as 1 and Sequence Number as y. The server puts all the above information into a packet segment (SYN+ACK packet segment) and sends the packet to the client. At this time, the server enters the SYN_RECV state. Third handshake: The client receives the SYN+ACK packet from the server. Then set the Acknowledgment Number to Y +1, and send an ACK packet segment to the server. After this packet segment is sent, both the client and server enter the ESTABLISHED state and complete the TCP three-way handshake.
After completing the three-way handshake, the client and server can begin to transfer data. That’s the overview of the TCP three-way handshake. The connection between the client and the server is disconnected after the communication ends, and four times of separation confirmation is required.
First break up: Host 1 (either the client or the server), set Sequence Number and Acknowledgment Number, and send a FIN packet segment to host 2. Host 1 enters the FIN_WAIT_1 state. This means that host 1 has no data to send to host 2; Second break up: Host 2 receives the FIN packet segment sent by host 1, and sends an ACK packet segment to host 1. This Acknowledgment Number is the Sequence Number plus 1. Host 1 enters the FIN_WAIT_2 state. Host 2 tells Host 1 that I “agree” to your shutdown request; Third breakup: Host 2 sends a FIN packet segment to host 1 to close the connection, and host 2 enters the LAST_ACK state. After receiving the FIN packet segment from host 2, host 1 sends an ACK packet segment to host 2. Then host 1 enters the TIME_WAIT state. After receiving an ACK packet from host 1, host 2 closes the connection. If host 1 does not receive a reply after waiting for 2MSL, it proves that the Server has been properly shut down. Then, host 1 can close the connection.
- The IP address
IP addresses (IPv4 addresses) are represented by 32-bit positive integers and are processed in binary format inside the computer. In daily life, we divide 32-bit IP addresses into groups of 8 bits and each group is “.” And then convert each group of numbers to decimal numbers
An IP address contains the network id and host ID, such as 172.112.110.11
172.112.110 is the network ID, and the network ids on the same network segment must be the same.11 is the host ID. The host IDS on the same network segment must be unique
- IPv6
IPv6 (IP Version 6) is a standardized Internet protocol to solve the problem of IPv4 address exhaustion. An IPv4 address contains four 8-bit bytes, that is, 32 bits. The length of an IPv6 address is four times that of the original address, or 128 bits, which is generally written as eight 16-bit bytes.
- DNS
We usually visit a website, an application, not with IP to access, but with a domain name. So how do domain names relate to IP addresses?
The Domain Name System is the Domain Name System
Take visiting zh.wikipedia.org as an example:
The client sends the query packet “query zh.wikipedia.org” to the DNS server. The DNS server first checks its cache and returns the result if there is a record. If the records are aged or do not exist, the DNS server sends a query message “query zh.wikipedia.org” to the root DNS server, and the root DNS server returns the IP address of the TOP-LEVEL DNS server in the top-level DOMAIN. The DNS server sends the query message “query zh.wikipedia.org” to the top-level DNS server in the.org domain to obtain the authoritative DNS server address of the secondary domain. The DNS server sends the query message “query zh.wikipedia.org” to the authoritative DNS server in the.wikipedia.org domain, obtains the A record of host ZH, stores it in its cache, and returns it to the client.
How to create a TCP service using Nodejs?
Before we do that, we need to understand the concept of sockets.
Socket is an abstraction layer between the application layer and the transport layer. It abstracts the complex operations of THE TCP/IP layer into several simple interfaces for the application layer to call the implemented processes to communicate in the network, such as create, LISTEN, Accept, connect, etc. Read, write, and so on.
There are various modules related to network in Node. HTTP is an application-layer module, which mainly codec data according to specific protocols. Net for the transmission layer module, mainly responsible for the transmission of coded application layer data; HTTPS is a comprehensive module (covering HTTP/TLS /crypto, etc.) that is mainly used to ensure data security
- Example Create a TCP server
const net = require('net');
const HOST = '127.0.0.1';
const PORT = 7777;
// Create a TCP server instance and call listen to start listening on the specified port
// net.createserver () has one parameter, which is a callback that listens for connection establishment
net.createServer((socket) = > {
const remoteName = `${socket.remoteAddress}:${socket.remotePort}`;
// A connection has been established. The callback function returns a socket object.
console.log(`${remoteName}Connect to this server ');
// Receive the message
socket.on('data'.(data) = > {
console.log(`${remoteName} - ${data}`)
// Send a message to the client
socket.write('What did you say? is${data}? `);
});
/ / close
socket.on('close'.(data) = > {
console.log(`${remoteName}Connection closed ')}); }).listen(PORT, HOST);console.log(`Server listening on ${HOST}:${PORT}`);
Copy the code
- Creating a TCP client
const net = require('net');
const HOST = '127.0.0.1';
const PORT = 7777;
const client = new net.Socket();
const ServerName = `${HOST}:${PORT}`;
let count = 0;
client.connect(PORT, HOST, () = > {
console.log('Successfully connected to${ServerName}`);
// Send data to the server
const timer = setInterval(() = > {
if (count > 10) {
client.write('I'm all right. Goodbye.');
clearInterval(timer);
return;
}
client.write('Ma Dongmei' + count++);
}, 1000)});// Receive the message
client.on('data'.(data) = > {
console.log(`${ServerName} - ${data}`);
// Close the connection
// client.destroy();
});
// Close the event
client.on('close'.() = > {
console.log('Connection closed');
});
client.on('error'.(error) = > {
console.log(error);
})
Copy the code
- Run the
node tcp-server.js
node tcp-client.js
How to create a UDP service using NodeJs?
- Example Create a UDP server
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message'.(msg, remote) = > {
console.log(`${remote.address}:${remote.port} - ${msg}`)
server.send(` received! `, remote.port, remote.address);
})
server.on('listening'.() = > {
const address = server.address()
console.log(`Server listening on ${address.address}:${address.port}`);
})
server.bind(44444);
Copy the code
- Creating a UDP client
const dgram = require('dgram')
const message = Buffer.alloc(5.'robozy')
const client = dgram.createSocket('udp4')
client.send(message, 0, message.length, 44444.'localhost'.(err, bytes) = > {
console.log('Sent successfully${bytes}Byte `);
// client.close()
}
)
client.on('message'.(buffer) = > {
console.log(buffer.toString())
})
Copy the code
- Run the
node udp-server.js
node udp-client.js
HTTP
HyperText Transfer Protocol (HTTP) is used to Transfer HyperText from a WWW server to a local browser. It can make the browser more efficient and reduce network traffic. It not only ensures that the computer can transfer the hypertext document correctly and quickly, but also determines which part of the transferred document and which part of the content should be displayed first (for example, text before graphics). HTTP is an application-layer communication protocol between a client browser or other program and a Web server. All hypertext information is stored on the Web server on the Internet, and the client needs to transfer the hypertext information to be accessed through THE HTTP protocol. HTTP contains commands and transmission information. It can be used not only for Web access, but also for communication between other Internet/Intranet application systems. In this way, hypermedia access of various application resources can be integrated. The web address we enter in the browser address bar is called a Uniform Resource Locator (URL). Just as every home has an address, every web page has an Internet address. When you type a URL into the browser’s address box or click on a hyperlink, the URL determines the address to browse to. The browser uses hypertext transfer Protocol (HTTP) to extract the Web code of the site on the Web server and translate it into a beautiful Web page.
What does a full HTTP communication look like?
- Establishing a TCP Connection
Before the HTTP work can begin, the client first establishes a connection to the server over the network, which is done through TCP. HTTP is an application-layer protocol at a higher level than TCP. According to rules, connections can be made to high-level protocols only after low-level protocols are established. Therefore, TCP connections must be established first.
- The client sends a request command to the server
Once a TCP connection is established, the client sends a request command to the server; For example, GET/info HTTP/1.1
- The client sends the request header
After the client sends its request, it sends some other information to the server in the form of a header. After that, the client sends a blank line to notify the server that it has finished sending the header.
- Server reply
After the client sends a request to the server, the server returns a response from the client. For example: HTTP/1.1 200 OK The first part of the response is the protocol version number and the response status code
- The server returns a response header
Just as the client sends information about itself along with the request, the server sends data about itself and the requested document to the user along with the response;
- The server sends data to the client
After the server sends the header to the client, it sends a blank line indicating the end of the header. It then sends the actual data requested by the user in the format described in the Content-type response header.
- The server closed the TCP connection. Procedure
Normally, once the server returns the request to the client, it closes the TCP Connection. Then, if the client or server adds the line Connection:keep-alive to its header, the TCP Connection will remain open after it is sent. The client can continue to send requests over the same connection. Staying connected saves the time needed to establish a new connection for each request and saves network bandwidth.
What are the features of THE HTTP protocol?
- Communication is achieved through the exchange of request and response
The protocol states that the request is sent from the client and the server responds to the request and returns.
- stateless
HTTP is a stateless protocol. At the pure HTTP level, the protocol does not persist requests or responses that have been sent
- Use cookies for state management
The server may return headers with set-cookies, so when the client receives the response, it will plant cookies locally. The next time you send a request to the server, you carry these cookies with you.
- Locate resources by URL
Here’s a distinction between a URI and a URL.
URI: A uniform resource identifier (URI). For example, if your id number is XXXXXXX, which is unique among all people, this id number identifies you, then it is a URI URL: Uniform resource locator, such as Beijing/Chaoyang district/XXXX/XXXX/XXXXX, through this string of information to locate you, then this is the URL
A URL is somewhat similar to a URI implemented by locating.
For example, there is a parent class called URI that uniquely identifies an ID. Some people like to inherit a URI and do it through location; Some people like to inherit urIs by name.
- Identify your intentions in a variety of ways
This refers to various HTTP methods, such as GET, POST, PUT, DELETE, and so on.
- A persistent connection
In the initial version of the HTTP protocol, the TCP connection had to be broken for each HTTP communication, which added a lot of unnecessary connection establishment overhead. To address the above TCP connection issues, HTTP/1.1 supports persistent connections. The TCP connection is maintained as long as either end does not explicitly request to disconnect the connection. Designed for multiple request and response interactions after establishing a TCP connection. In HTTP/1.1, all connections are persistent by default.
This means that by default, a TCP Connection will not be disconnected. Only if a Connection: close is declared in the request header will the Connection be closed after the request is completed.
- Pipeline mechanism
Pipelining is introduced in version 1.1, which enables clients to send multiple requests simultaneously within the same TCP connection.
For example, a client needs to request two resources. The previous approach was to send A request and wait for A response from the server within the same TCP connection before sending B request. The pipe mechanism allows the browser to make A request and B request simultaneously, but the server responds to A request first and responds to B request after completion.
However, modern browsers generally do not enable this configuration, and this mechanism can cause queue blocking. Because responses are sequential, if the first HTTP request in a TCP connection responds very slowly, it will block the response of subsequent HTTP requests.
So by default, only one HTTP request is made for a TCP connection at a time.
Why did I hear that Chrome supports up to six requests for the same domain?
That’s because Chrome allows up to six TCP connections to be opened simultaneously.
So what is the main difference between HTTP 1.0/1.1/2.0 and concurrent requests?
- HTTP / 1.0
Each TCP connection can only send one request. When the server responds, the connection is closed and the next request requires a TCP connection.
- HTTP / 1.1
The default is a continuous Connection (TCP Connection is not closed by default, can be reused by multiple requests, do not declare Connection: keep-alive). The efficiency of THE HTTP protocol was further improved by adding a pipeline mechanism that allows multiple requests to be sent simultaneously within the same TCP connection, increasing concurrency, but all data traffic within the same TCP connection is carried out sequentially. The response is slow and there will be many requests queued, causing a “queue head jam”.
- HTTP / 2.0
Adding duplex mode, that is, not only the client can send multiple requests at the same time, but also the server can process multiple requests at the same time, solving the problem of queue head congestion. Multiplexing is used to process multiple requests concurrently on the same connection, and the number of concurrent requests is several orders of magnitude larger than HTTP1.1. Add the function of server push, and the server sends data to the client without request.
All kinds of Headers
Cache-Control
You can manipulate how the Cache works by specifying the cache-control header field.
- Cache-Control: public
When you specify the use of the public directive, it is clear that other users can also use the cache.
- Cache-Control: private
When a private directive is specified, the response objects only to a particular user, as opposed to the behavior of the public directive. The cache server provides caching of resources for this particular user, and the proxy server does not return cached requests from other users.
- Cache-Control: no-cache
You can store resources on the client, and each time you have to go to the server for an expiration check to determine whether to get new resources from the server (200) or to use the client cache (304). This is called a negotiation cache.
- Cache-Control: no-store
Never store resources on the client, always get resources from the original server.
- Cache-control: max-age=604800 (unit: second)
When the request sent by the client contains the max-age directive, if the cache time value of the cached resource is determined to be smaller than the specified time, the client receives the cached resource. In addition, when the max-age value is specified as 0, the cache server usually needs to forward the request to the source server.
In the HTTP/1.1 version, when the Expires header field is present at the same time, the max-age directive is preferred and the Expires header field is ignored
- Cache-control: s-maxage=604800 (unit: second)
The function of the S-MaxAge directive is the same as that of the max-Age directive, except that the S-MaxAge directive only applies to a common cache server (typically a proxy) that is used by multiple users. When the S-maxAge directive is used, the Expires header field and the max-age directive are ignored
Connection
- Connection: close
The default connections for HTTP/1.1 are persistent. If the server wants to explicitly disconnect the Connection, the Connection header field is set to close.
- Connection: Keep-Alive
The default connections for HTTP versions prior to HTTP/1.1 are non-persistent. To do this, if you want to maintain persistent connections over older versions of the HTTP protocol, you need to specify the value of the Connection header field as keep-alive.
Date
Indicates the date and time when the HTTP packet is created. Date: Mon, 10 Jul 2021 15:50:06 GMT HTTP/1.1 uses the Date and time format specified in RFC1123.
Pragma
The Pragma header field is a relic field from before HTTP/1.1 and is defined only for backward compatibility with HTTP/1.0.
- Pragma: no-cache
This header field belongs to the generic header field, but is used only in requests sent by clients that require all intermediate servers not to return cached resources.
Using cache-control: no-cache to specify how the Cache is handled is ideal if all intermediate servers can be benchbenched to HTTP/1.1. However, it is impractical to fully understand the HTTP protocol version used by all intermediate servers, so requests are sent with both of the following header fields:
Cache-Control: no-cache
Pragma: no-cache
Copy the code
Accept
- Accept: text/html, application/xhtml+xml, application/xml;
The Accept header field notifies the server of the media types that the user agent can handle and their relative priority. You can specify multiple media types at once using the form type/subtype.
- Accept-Encoding: gzip, deflate
The accept-encoding header field is used to tell the server which content encodings are supported by the user agent and the priority of the content encodings. Multiple content encodings can be specified at one time or any Encoding can be specified using the asterisks (*) as wildcards.
Gzip indicates that the entity is encoded in GNU Zip. Compress indicates that the entity is compressed in Unix. Deflate indicates that the entity is compressed in Zlib. If there is no Content-Encoding header field, this Encoding is used by default
Host
- Host: www.baidu.com
- Tells the server the Internet host and port number of the requested resource.
- The Host header field is the only HTTP/1.1 header field that must be included in a request.
- If the server does not have a Host name, send a null value Host:.
If-Modified-Since
A request header field in the form of if-XXX is called a conditional request. After receiving a conditional request, the server will execute the request only if it determines that the specified condition is true.
- If-Modified-Since: Mon, 10 Jul 2021 15:50:06 GMT
Used to verify the availability of local resources owned by the agent or client. If none of the requested resources has been updated after specifying the date and time of the if-Modified-Since field value, return a response with status code 304 Not Modified
ETag
- ETag: “aaaa-1234”
The header field ETag tells the client the identity of the entity. It is a way to uniquely identify a resource as a string. The server assigns ETag values for each resource. In addition, the ETag value needs to be updated when the resource is updated. There are no uniform algorithmic rules for generating ETag values, but they are simply assigned by the server.
If-None-Match
- If-None-Match: “robozy”
When the entity tag (ETag) value used to specify the value of the if-none-match field does not Match the ETag of the requested resource, it tells the server to process the request.
User-Agent
- The user-agent: Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36
The header field user-agent communicates information to the server such as the browser that created the request and the name of the User Agent. When a request is made by a web crawler, it is possible to add the E-mail address of the crawler author to the field. In addition, if the request goes through a proxy, the proxy server name is also likely to be added in the middle.
Allow
- Allow: GET, HEAD
The header field Allow is used to inform the client that all HTTP methods specified by the request-URI can be supported. When receiving an unsupported HTTP Method, the server returns the status code 405 Method Not Allowed as a response. At the same time, all supported HTTP methods are written to the header field Allow and returned.
Content-Encoding
- Content-Encoding: gzip
The header field content-Encoding tells the client server what Content Encoding to choose for the body of the entity. Content encoding refers to compression without losing entity information.
Content-Type
- Content-Type: text/html; charset=UTF-8
The header field Content-type specifies the media Type of the object within the entity body. As with the header field Accept, the field value is assigned in the form type/ subType.
Expires
- Expires: Mon, 10 Jul 2021 15:50:06 GMT
The header field Expires tells the client when the resource Expires. After receiving a response with the header field Expires, the cache server responds to the request with a cache. A copy of the response is saved until the specified time. When the specified time exceeds, the cache server will turn to the source server to request resources when the request is sent.
Set-Cookie
- Set-Cookie: userId=11111; expires=Mon, 10 Jul 20121 15:50:06 GMT; path=/;
- NAME=VALUE: indicates the NAME and VALUE of the cookie
- Expires =DATE: The expiration DATE of a Cookie (default: until the browser closes if not specified)
- Path =PATH: File directory used to limit the sending range of specified cookies.
- Domain = domain name: specifies the valid domain name of the cookie (if not specified, default is the domain name of the server that created the cookie).
- Secure: Cookies are sent only for Secure HTTPS communication
- HttpOnly: Makes cookies inaccessible to JavaScript scripts
How do I create an HTTP service using NodeJs?
- http-server.js
const http = require('http')
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end('Hello World')
}).listen(80.'127.0.0.1')
console.log('Server running at http://127.0.0.1:80/)
Copy the code
- Browser access
http://127.0.0.1:80/
- Use the curl access
The curl -v http://127.0.0.1:80
Take a look at the request message
// rebuild URL to: http://127.0.0.1:80/ * Trying 127.0.0.1... * TCP_NODELAY set * Connected to 127.0.0.1 (127.0.0.1) port 80 (#0) // The client sends a request packet to the server > GET/HTTP/1.1 > Host: 127.0.0.1:80 > user-agent: curl/7.54.0 > Accept: */* > < HTTP/1.1 200 OK < content-type: text/plain < Date: Wed, 04 Aug 2021 15:55:55 GMT < Connection: keep-alive < Keep-Alive: timeout=5 < Transfer-Encoding: Chunked < * Connection #0 to host 127.0.0.1 left intact Hello World%Copy the code
- htttp-client.js
const http = require('http')
const options = {
hostname: '127.0.0.1'.port: 80.path: '/'.method: 'GET'
}
const req = http.request(options, (res) = > {
console.log(`Status=${res.statusCode}, Headers=The ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8')
res.on('data'.(data) = > {
console.log(data)
})
})
req.end()
Copy the code
The deployment of
The server
When it comes to deployment, you have to have your own server…
www.aliyun.com/daily-act/e…
Choose ecS server, pay by volume/month/year, any image can be selected.
Linux installation Nodejs
- Download the Installation Package
Wget HTTP: / / https://nodejs.org/dist/v10.9.0/node-v10.9.0-linux-x64.tar.xz
- Unpack the
The tar xf node - v10.9.0 - Linux - x64. Tar. Xz
- Setting a soft link
Ln -s /root/node-v10.9.0-linux-x64/bin/node /usr/local/bin/node ln -s /root/node-v10.9.0-linux-x64/bin/npm /usr/local/bin/npm
- View the Node version and NPM version
node -v
npm -v
- Set the NPM source
npm config set registry https://registry.npm.taobao.org
- Install the PM2 on the server
NPM install -g pm2 ln -s /root/node-v10.9.0-linux-x64/bin/pm2 /usr/local/bin/
- Configure SSH
- Generate a key pair locally:
ssh-keygen -t rsa
demo_id_rsa - To put the public key on the server:
SCP ~ /. SSH/demo_id_rsa. Pub [email protected]: / root /. SSH/authorized_keys
- Modifying SSH Configurations
vi ~/.ssh/config
Host Robozy HostName 39.107.238.161 User root Port 22 IdentityFile ~/. SSH /demo_id_rsaCopy the code
- Modify SSH configurations on the server
vim /etc/ssh/sshd_config
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys
- Finally, you can SSH login!
ssh robozy
- Synchronize the local code to the server
rsync -avzp -e "ssh" ./Internet/ robozy:/root/app
- Start HTTP on the server
pm2 start /root/app/http-server.js
- Local modify publish command
10.1 Creating the deploy.sh file
#! /bin/bash
HOST=robozy
rsync -avzp -e "ssh" ./Internet/ $HOST:/root/app
ssh $HOST "pm2 restart /root/app/http-server.js"
echo 'deploy success'
Copy the code
10.2 Initializing the NPM Command
NPM init added scripts “deploy”: “./deploy.sh”
10.3 release
npm run deploy
- Example Change the listening host of http-server
const http = require('http')
const host = '0.0.0.0';
const port = 80;
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end('Hello World')
}).listen(port, host)
console.log(`Server running at http://${host}:${port}/ `)
Copy the code
- Port 80 was added to the ECS security group
- Check whether the server is listening to port 80
netstat -tpln
- Access by IP + port
39.107.238.161:80
Co-creating author: Zhang Xiaoxu Gold excavation homepage: juejin.cn/user/852876…