socket.bind(options[, callback])


对于 UDP 套接字,使 dgram.Socket 监听命名 port 和可选 address 上的数据报消息,这些消息作为作为第一个参数传入的 options 对象的属性传入。 如果未指定 port0,则操作系统将尝试绑定到随机端口。 如果未指定 address,则操作系统将尝试监听所有地址。 一旦绑定完成,则会触发 'listening' 事件并调用可选的 callback 函数。

options 对象可能包含 fd 属性。 当设置了大于 0fd 时,则将使用给定的文件描述符环绕现有的套接字。 在这种情况下,portaddress 的属性将被忽略。

同时指定 'listening' 事件监听器并将 callback 传给 socket.bind() 方法无害但不是很有用。

options 对象可能包含额外的 exclusive 属性,当将 dgram.Socket 对象与 cluster 模块一起使用时会使用该属性。 当 exclusive 设置为 false(默认)时,集群工作进程将使用相同的底层套接字句柄,允许共享连接处理职责。 但是,当 exclusivetrue 时,则句柄未共享,尝试共享端口会导致错误。

绑定的数据报套接字使 Node.js 进程保持运行以接收数据报消息。

如果绑定失败,则生成 'error' 事件。 在极少数情况下(例如,尝试与关闭的套接字绑定),可能会抛出 Error

监听独占端口的套接字示例如下所示。

socket.bind({
  address: 'localhost',
  port: 8000,
  exclusive: true,
});

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.

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.

Specifying both a 'listening' event listener and passing a callback to the socket.bind() method is not harmful but not very useful.

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.

A bound datagram socket keeps the Node.js process running to receive datagram messages.

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,
});