In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/03 Report--
TCP services are very common in network applications. At present, most applications are based on TCP. The net module provides an asynchronous network wrapper for TCP network programming, which includes methods for creating servers and clients. This article will introduce the net module in nodeJS in detail.
IP test
[net.isIP (input)]
Test whether the input is an IP address. Returns 0 if the string is invalid. Return 4 in IPV4 and 6 in IPV6
Var net = require ('net'); console.log (net.isIP (' 1.1.1.1')); / / 4console.log (net.isIP ('1.1')); / / 0console.log (net.isIP (' AD80::ABAA:0000:00C2:0002')); / / 6
[net.isIPv4 (input)]
If the address entered is IPV4, return true, otherwise return false
Var net = require ('net'); console.log (net.isIPv4 (' 1.1.1.1')); / / trueconsole.log (net.isIPv4 ('1.1')); / / false
[net.isIPv6 (input)]
If the address entered is IPV6, return true, otherwise return false
Var net = require ('net'); console.log (net.isIPv6 (' 1.1.1.1')); / / trueconsole.log (net.isIPv6 ('AD80::ABAA:0000:00C2:0002')); / / true server
[net.createServer ([options] [, connectionListener])]
Create a TCP server with the following parameters
Options allowHalfOpen: false (default). If true, socket will not automatically send FIN packets when the other side socket sends FIN packets. Socket becomes unreadable but writable (half-closed) pauseOnConnect: false (default), if true, the associated socket will be paused when the connection arrives. It allows connections to be passed between processes when the initial process does not read data. Call resume () to read data from the paused socket connectionListener automatically creates a listener for the 'connection' event
Var server = net.createServer (function () {})
[server.listen (port [, host] [, backlog] [, callback])]
Start accepting connections between the designated port port and the host host. If you ignore the host host, the server will accept direct connections to any IPv4 address (INADDR_ANY). If the port is 0, a random port is assigned
Backlog (Backlog) is the maximum length of the connection waiting queue. The actual length is set by the operating system through sysctl, such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511
The 'listening' event is triggered when the server is bound. The last parameter, callback, will act as a listener for the 'listening' event
Some users will encounter an EADDRINUSE error, which indicates that another server is already running on the requested port. The way to deal with this situation is to wait a while and try again.
Server.listen (6000)
[server.close ([callback])]
The server stops receiving new connections and maintains existing connections. When all connections are completed, the server shuts down and the 'close' event is triggered. You can pass a callback function to listen for the 'close' event. If present, the callback function will be called with an error (if any) as the only argument
[server.address ()]
The operating system returns the bound address, protocol family name, and server port. It is useful to find out which port has been bound by the system
[note] do not call server.address () until the 'listening' event is triggered.
Server.listen (function () {/ / {address:'::', family: 'IPv6', port: 53806} console.log (server.address ();})
[server.maxConnections]
When this option is set, new connections are rejected when the number of server connections exceeds the number
Once you have sent socket to a child process with the child_process.fork () method, this option is not recommended
[server.getConnections (callback)]
Gets the number of active connections to the server asynchronously. Valid when socket is sent to child process
The callback function has two arguments, err and count
Server.getConnections (function (err,count) {console.log (count); / / 0})
[event listening]
Triggered when the server invokes server.listen binding
[event connection]
{Socket object} connection object
It is triggered when a new connection is created. Socket is an instance of net.Socket
[event close]
Triggered when the server is shut down
[note] if there is a connection, this event will not be triggered until all connections are closed
[event error]
Triggered when an error occurs
Client
[net.connect (options [, connectionListener])]
[net.createConnection (options [, connectionListener])]
The alias for connect () is the createConnection () method
This method returns a new 'net.Socket', and connects to the specified address and port. When the socket is established, the 'connect' event will be triggered. It's the same way as' net.Socket'.
For TCP sockets, the parameter options is as follows
Port: the port on which the client connects to the Port (must) host: the client wants to connect to the host. Default 'localhost'localAddress: local interface bound to the network connection localPort: local port bound to the network connection family: IP stack version. Default 4
For local socket, the parameter options is as follows
Path: the path to which the client connects (required) var client = net.connect ({port: 5000}, function () {}); Socket
[new net.Socket ([options])]
Construct a new socket object
The options object has the following default values:
{fd: null allowHalfOpen: false, readable: false, writable: false}
The parameter fd allows you to specify an existing file descriptor. Set readable and / or writable to true to allow reading or writing on this socket (only if the parameter fd is valid)
[socket.connect (port [, host] [, connectListener])]
[socket.connect (path [, connectListener])]
Open a connection using the incoming socket. If port port and host host,TCP socket are specified, socket will be opened. If you omit the parameter host, the default is localhost. If path,socket is specified, it will be opened by the unix socket of the specified path
The parameter connectListener will be added as a listener to the 'connect' event
[socket.write (data [, encoding] [, callback])]
Send data on socket. The second parameter specifies the encoding of the string, which defaults to UTF8 encoding
If all data is successfully flushed to the kernel buffer, true is returned. If all or part of the data is in the user's memory, return false. Triggers' drain' when the buffer is empty
When the data is finally fully written, the optional callback parameters are executed, but not necessarily immediately
[socket.end ([data] [, encoding])]
Half-close the socket. For example, it sends a FIN packet. Maybe the server is still sending data.
If the parameter data is not empty, it is equivalent to calling socket.end () after calling socket.write (data,encoding)
[socket.destroy ()]
Make sure that there is no Iripple O activity on this socket. Needed only if an error occurs
[socket.pause ()]
Pause reading of data. That is, the data event is no longer triggered. Very useful for controlling uploads
[socket.resume ()]
I want to resume reading data after calling pause ()
[socket.setTimeout (timeout [, callback])]
When the socket is idle for more than timeout milliseconds, set the socket to timeout. When the idle timeout event is triggered, the socket will receive the 'timeout' event, but the connection will not be disconnected. The user must manually call the socket of end () or destroy ().
If timeout = 0, the existing idle timeout is disabled. The optional callback parameter will be added as an one-time listener for the 'timeout' event
[socket.setNoDelay ([noDelay])]
Disables the Nagle algorithm. By default, TCP connections use the nag algorithm, which buffers data before sending it. Setting noDelay to true will send data immediately when socket.write () is called. The default value of noDelay is true
[socket.setKeepAlive ([enable] [, initialDelay])]
Disable / enable the persistent connection feature and optionally set the initial delay before sending the first persistent probe on the idle socket. Default false
Set initialDelay (milliseconds) to set the delay between the last packet received and the first persistent probe. Setting initialDelay to 0 will retain the default (or previous) value. Default value is 0
[socket.address ()]
The operating system returns the bound address, protocol family name, and server port. The returned object has three properties, such as {port: 12346, family: 'IPv4', address:' 127.0.0.1'}
[socket.remoteAddress]
Remote IP address string
[socket.remoteFamily]
Remote IP protocol family string
[socket.remotePort]
Remote port, numeric representation
[socket.localAddress]
The local IP address to which the remote client is connecting, and the string represents
[socket.localPort]
Local port address, represented by a number
[socket.bytesRead]
Number of bytes received
[socket.bytesWritten]
Number of bytes sent
[event lookup]
This event is triggered after the domain name is resolved, but before the connection. Not applicable to UNIX sokcet
Err {Error | Null} wrong object address {String} IP address. Family {String | Null} address type
[event connect]
Triggered when a socket connection is successfully established,
[event data]
{Buffer object}
Triggered when data is received. Parameter data can be Buffer or String
When Socket triggers an 'data' event, if there is no listener, the data will be lost
[event end]
This event is triggered when the other end of the socket sends a FIN packet
[event timeout]
Triggered when the socket idle timeout only indicates that the socket is idle. The user must manually close the connection
[event drain]
Triggered when the write cache is empty. Can be used to control upload
[event error]
Triggered when an error occurs
[event close]
Had_error {Boolean} true if socket transmission error
Triggered when the socket is completely closed. The parameter had_error is boolean, which indicates whether socket is shut down because of a transmission error
Simple server
[server]
/ / server.jsvar net = require ('net'); var server = net.createServer (function (socket) {socket.write ("Hi!\ n"); socket.on ("data", function (data) {console.log (data.toString ());}); socket.on ("end", function () {console.log (' client offline!') ;}); socket.on ('error', function () {console.log (' unexpected error!') ;}); server.listen (8080)
[client]
/ / client.jsvar net = require ('net'); var client = net.connect ({port: 8080}, function () {client.name =' client 1'; client.write (client.name +'is online! Client.end (client.name +'is offline! Client.on ("data", function (data) {console.log (data.toString ());});})
Simple chat room
[server]
/ / chatServer.jsvar net = require ('net'); var I = 0 socket.write / save client var clientList = []; var server = net.createServer (function (socket) {socket.name =' user'+ (+ + I); socket.write ('[chat room prompt] Welcome'+ socket.name +'\ n'); / / Update client array clientList.push (socket) Function showClients () {console.log ('[current online user]:'); for (var iTuno
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.