[英]Can anyone help me with the math for an express port randomizer
我的机器人一直在破坏数据并随机崩溃并发现了问题,就是这段代码:
Math.floor(Math.random()*6000)
谁能帮我这个? 另外,这是我的整个 express.js 文件:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('DSB is online')
})
app.listen(port, () => {
console.log(`BOT listening at http://localhost:${port}`)
})
它说 3000 因为那是原始的。 我已经改变了它,这几乎就是它所说的。
您可以将随机数更改为最小值。 正如CertainPerformance 在他们的评论中提到的那样,从1000(或者可能是1024)而不是零开始是个好主意。 您当前的代码将返回一个介于 0 和 6000 之间的数字(包括 0 但不包括 6000)。
下面的 function 将生成一个介于min
和max
之间的随机 integer。
function randomInt(min = 1024, max = 6000) {
if (min > max) {
[min, max] = [max, min]
}
return Math.floor((Math.random() * ((max - min) + 1)) + min)
}
randomInt() // => 5302
你可以像这样使用它:
app.get('/', (req, res) => {
res.send('DSB is online')
})
const server = app.listen(randomInt(), () => {
console.log(`BOT listening on port ${server.address().port}`)
// => BOT listening on port 5981
})
在 Express 中,如果你想随机分配一个端口,你可以简单地监听端口0
:
app.get('/', (req, res) => {
res.send('DSB is online')
})
const server = app.listen(0, () => {
console.log(`BOT listening on port ${server.address().port}`)
// => BOT listening on port 58319
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.