socket.bind(options[, callback])
options<Object> 必填。支持以下属性:callback<Function>
对于 UDP 套接字,会使 dgram.Socket 在名为 port 的端口和可选的 address 上监听数据报消息,这些属性作为 options 对象的属性传递,options 对象作为第一个参数传入。如果未指定 port 或端口为 0,操作系统将尝试绑定到一个随机端口。如果未指定 address,操作系统将尝试在所有地址上监听。一旦绑定完成,将触发 'listening' 事件,并调用可选的 callback 函数。
【For UDP sockets, causes the dgram.Socket to listen for datagram
messages on a named port and optional address that are passed as
properties of an options object passed as the first argument. If
port is not specified or is 0, the operating system will attempt
to bind to a random port. If address is not specified, the operating
system will attempt to listen on all addresses. Once binding is
complete, a 'listening' event is emitted and the optional callback
function is called.】
options 对象可能包含一个 fd 属性。当设置的 fd 大于 0 时,它将使用给定的文件描述符封装现有的套接字。在这种情况下,port 和 address 的属性将被忽略。
【The options object may contain a fd property. When a fd greater
than 0 is set, it will wrap around an existing socket with the given
file descriptor. In this case, the properties of port and address
will be ignored.】
同时指定一个 'listening' 事件监听器并向 socket.bind() 方法传递 callback 并不会造成问题,但没有太大用处。
【Specifying both a 'listening' event listener and passing a
callback to the socket.bind() method is not harmful but not very
useful.】
options 对象可能包含一个额外的 exclusive 属性,当使用 cluster 模块的 dgram.Socket 对象时会用到该属性。当 exclusive 设置为 false(默认值)时,集群工作进程将使用相同的底层套接字句柄,从而可以共享连接处理任务。然而,当 exclusive 为 true 时,该句柄不共享,尝试端口共享会导致错误。使用 reusePort 选项设置为 true 创建的 dgram.Socket 在调用 socket.bind() 时会导致 exclusive 始终为 true。
【The options object may contain an additional exclusive property that is
used when using dgram.Socket objects with the cluster module. When
exclusive is set to false (the default), cluster workers will use the same
underlying socket handle allowing connection handling duties to be shared.
When exclusive is true, however, the handle is not shared and attempted
port sharing results in an error. Creating a dgram.Socket with the reusePort
option set to true causes exclusive to always be true when socket.bind()
is called.】
绑定的数据报套接字会保持 Node.js 进程运行以接收数据报消息。
【A bound datagram socket keeps the Node.js process running to receive datagram messages.】
如果绑定失败,会生成一个 'error' 事件。在少数情况下(例如尝试与已关闭的套接字绑定),可能会抛出 Error。
【If binding fails, an 'error' event is generated. In rare case (e.g.
attempting to bind with a closed socket), an Error may be thrown.】
监听独占端口的套接字示例如下所示。
【An example socket listening on an exclusive port is shown below.】
socket.bind({
address: 'localhost',
port: 8000,
exclusive: true,
});