socket.bind([port][, address][, callback])
port<integer>address<string>callback<Function> 无参数。在绑定完成时调用。
对于 UDP 套接字,使 dgram.Socket 在指定的 port 和可选的 address 上监听数据报消息。如果未指定 port 或为 0,操作系统将尝试绑定到一个随机端口。如果未指定 address,操作系统将尝试监听所有地址。绑定完成后,将触发 'listening' 事件,并调用可选的 callback 函数。
【For UDP sockets, causes the dgram.Socket to listen for datagram
messages on a named port and optional address. 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.】
同时指定一个 '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.】
绑定的数据报套接字会保持 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.】
UDP 服务器监听端口 41234 的示例:
【Example of a UDP server listening on port 41234:】
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.error(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(41234);
// Prints: server listening 0.0.0.0:41234const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.error(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(41234);
// Prints: server listening 0.0.0.0:41234