TCP
TCP is used for communication between the computer, through the preparation of client and server chat code, for the server and client work steps have a deep understanding. To implement TCP in Node, a NET module is provided. The NET module gives you an asynchronous network encapsulation that includes the ability to create servers and clients (called streams).
Example Creating a TCP server
-
net.createServer(options,connectionListener);
Create a TCP service with a callback listener that will execute when the connection arrives.
The parameter socket passed in is a socket, which helps us to realize the session. The socket corresponding to each client is different. Is a Duplex duplex flow that supports both read and write operations.
-
server.listen()
You can set the port for the service to listen to, the host name, and the backlog server to handle the maximum number of requests. The default is 511. There are also callback functions that are called when the service is successfully started
let net = require('net');
let server = net.createServer(function(socket){
...
})
server.listen(8080,'localhost'.function(){
console.log(`server start 8080`)
});Copy the code
You can then configure the server
Set the maximum number of links on a server
server.maxConnections = 6;Copy the code
Firing method when a connection is obtained
You want each request to come in with a hint of the maximum number of connections and the total number of connections
server.getConnections(function(err,count){socket.write(' The current maximum capacity${server.maxConnections}Now,${count}`)});Copy the code
Accept client data
-
Read client input
socket.on('data'.function(data){
console.log(data);
});Copy the code
-
Stop reading
socket.pause();Copy the code
-
Restore read
socket.resume();Copy the code
pipe&unpipe
When listening for input from the client, write the input from the client to the file content.
If there are two clients, there are two sockets, one of which is closed, and the other cannot be written in
let net = require('net');
let path = require('path');
let ws = require('fs').createWriteStream(path.join(__dirname,'./1.txt'));
let server = net.createServer(function(socket){
socket.pipe(ws,{end:false}); // So you can set this writable stream not to closesetTimeout(function(){
ws.end(); // 关闭可写流
socket.unpipe(ws); // 取消管道,就不能传输了
},5000)
});
server.listen(8080);Copy the code
Closing the Client
-
socket.end(); In addition to closing it manually, we can also call this method to close it.
Closing the Server
-
server.close();
The close event indicates that the server is no longer receiving new requests and the current one can continue to be used. The close event is executed when the client is completely shut down.
// The close event will only trigger server.on('close'.function(){
console.log('Server down');
})Copy the code
-
server.unref();
Unref () does not trigger the close event, the server is closed only when all clients are closed, and can still be closed if someone comes in (with a new request).
Example Creating a TCP client
-
Net.createconnection is used to create connections on the server side
let net = require('net');
let socket = net.createConnection({port:8080},function(){
socket.write('hello');
socket.on('data'.function(data){
console.log(data);
});
});Copy the code
HTTP
Node also provides a module to implement HTTP, called HTTP module, which encapsulates the efficient HTTP server and HTTP client, similar to the USE of NET module.
Creating an HTTP Server
-
request
This event is emitted when a client request arrives.
The most commonly used event is the Request event, and HTTP provides a shortcut to this event: http.createserver ([requestListener]).
-
Parameters of the res the req
The parameter req passed in is the request, which is a readable stream, and res is the response, which is a writable stream. The request and response are parsed through the socket.
There are two ways to create an HTTP server
-
The first kind of
let http = require('http');
let server = http.createServer();
server.on('request'.function(req,res){
req.on('end'.function(){
res.write('hello');
res.end('world');
});
});
server.listen(8080);Copy the code
-
You could write it this way
let http = require('http');
let server = http.createServer(function(req,res){
res.end('ok');
});
server.listen(8080);Copy the code
Shutting down the HTTP Server
let http = require('http');
let server = http.createServer(function(req,res){
});
server.on('close'.function(){
console.log('Server down');
});
server.listen(8080,'127.0.0.1'.function(){
console.log('Server listening! ') server.close(); / / close});Copy the code
Create an HTTP client
The HTTP module provides two functions, http.request and http.get, to make requests to the HTTP server as a client.
-
Http. request(options, callback) Initiates an HTTP request. It takes two arguments, option, which is an associative array-like object representing the request’s parameters, and callback, which is the request’s callback function.
let http = require('http');
let options = {
hostname:'localhost',
port:4000,
path: '/',
method:'get'// Tell the server what type of data I want to send you.'Content-Type':'application/x-www-form-urlencoded'.'Content-Length': 17}}letreq = http.request(options); // When the client receives a response from the server, req.on('response'.function(res){
res.on('data'.function(chunk){
console.log(chunk);
});
});
req.end('name=renee&&age=18');Copy the code
-
Get (options, callback) The HTTP module also provides a simpler method for handling GET requests: http.get. It is a simplified version of HTTP.request, the only difference being that http.get automatically sets the request method to get and does not require a manual call to req.end().
var http = require('http');
http.createServer(function(req,res){}).listen(3000);
http.get('http://www.baidu.com/index.html'.function(res){
console.log('get response Code :' + res.statusCode);
}).on('error'.function(e){
console.log("Got error: " + e.message);
})Copy the code