简体   繁体   English

谁能帮我计算一个快速端口随机器的数学

[英]Can anyone help me with the math for an express port randomizer

My bot has been corrupting data and randomly crashing and found the problem, it was this bit of code:我的机器人一直在破坏数据并随机崩溃并发现了问题,就是这段代码:

Math.floor(Math.random()*6000)

Can anyone help me with this?谁能帮我这个? Also, here is my entire express.js file:另外,这是我的整个 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}`)
})

It says 3000 because that's the original one.它说 3000 因为那是原始的。 I've changed it and that's almost what it says.我已经改变了它,这几乎就是它所说的。

You can change the random number to have a minimum value.您可以将随机数更改为最小值。 As CertainPerformance mentioned in their comment it's a good idea to start at 1000 (or maybe 1024) and not zero.正如CertainPerformance 在他们的评论中提到的那样,从1000(或者可能是1024)而不是零开始是个好主意。 Your current code will return with a number between 0 and 6000 (inclusive of 0 but not 6000).您当前的代码将返回一个介于 0 和 6000 之间的数字(包括 0 但不包括 6000)。

The following function will generate a random integer between a min and max value.下面的 function 将生成一个介于minmax之间的随机 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

And you can use it like this:你可以像这样使用它:

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

In Express, if you want to randomly assign a port, you can simply listen on port 0 :在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM