Node.js net.SocketAddress() 方法
Node.js Net 模块允许您创建 TCP 或 IPC 服务器和客户端。TCP 客户端发起连接请求,以与服务器建立连接。
语法: 以下是将 Net 模块导入到您的 Node.js 项目中的语法:
const <Variable_Name> = require('node:net');
const Net_Module = require('node:net');
net.SocketAddress()类为我们提供了网络套接字的详细地址。调用该类的SocketAddress()构造函数的语法如下:
Syntax:
const socket = new Net_Module.SocketAddress([options]);
参数:
- 选项: 它包括IP地址、端口、协议簇和流标签值。它是
<object>类型的,可选项。返回值:
-
socket.address:
<string>返回IP地址。 - socket.family:
<string>返回IP地址的协议簇,ipv4/ipv6。 - socket.flowlabel:
<number>返回一个ipv6流标签的数字。 - socket.port:
<number>返回端口号。
创建Node.js项目的步骤:
步骤1: 在终端中运行以下命令来设置Node.js项目的package.json:
npm init
步骤2: 创建一个描述代码的app.js文件。
步骤3: 现在将net模块导入到你的项目中,并开始编写代码。
如果你的系统中没有安装net模块,你可以使用以下命令将net模块安装到项目中:
npm i net
示例1: 让我们创建一个 net.SocketAddress() 类的对象并打印该对象。
// Program to create an object of SocketAddress class
// Importing the Net Module into project.
const Net_Module = require('node:net');
// Creating an object by calling the constructor
// of the class
const object = new Net_Module.SocketAddress();
// Printing the object
console.log(object);
输出:
SocketAddress {
address: '127.0.0.1',
port: 0,
family: 'ipv4',
flowlabel: 0
}
从输出中可以看出,该类的对象由四个属性组成,并为每个属性返回默认值。
示例2: 我们正在创建一个自定义选项对象,并将其传递给此构造函数,以了解它是否更改了所有属性的默认值。
// Program to create an object of SocketAddress class
// Importing the Net Module into project.
const Net_Module = require('node:net');
// Custom options object
const options = {
address:'142.38.75.36',
family:'ipv4',
port:200
};
// Creating the object by calling the constructor
// of the class and passing the custom options
// object to it
const object = new Net_Module.SocketAddress(options);
// Printing the object.
console.log(object);
输出:
SocketAddress {
address: '142.38.75.36',
port: 200,
family: 'ipv4',
flowlabel: 0
}
我们使用了一个随机的IP地址和端口号,并为该IP地址生成了Socket地址。
参考文献: https://nodejs.org/api/net.html#class-netsocketaddress
极客教程