node-minecraft-protocol/src/createServer.js

66 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

'use strict'
2016-04-27 19:27:32 -04:00
const Server = require('./server')
const NodeRSA = require('node-rsa')
2017-07-20 17:32:25 -04:00
const plugins = [
require('./server/handshake'),
require('./server/keepalive'),
require('./server/login'),
require('./server/ping')
]
module.exports = createServer
function createServer (options = {}) {
2017-07-20 17:32:25 -04:00
const {
host = undefined, // undefined means listen to all available ipv4 and ipv6 adresses
// (see https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback for details)
'server-port': serverPort,
2017-07-20 17:32:25 -04:00
port = serverPort || 25565,
motd = 'A Minecraft server',
'max-players': maxPlayersOld = 20,
maxPlayers: maxPlayersNew = 20,
2017-07-21 16:15:50 -04:00
version,
2017-07-20 17:32:25 -04:00
favicon,
customPackets
} = options
const maxPlayers = options['max-players'] !== undefined ? maxPlayersOld : maxPlayersNew
const optVersion = version === undefined || version === false ? require('./version').defaultVersion : version
2017-07-21 16:15:50 -04:00
const mcData = require('minecraft-data')(optVersion)
if (!mcData) throw new Error(`unsupported protocol version: ${optVersion}`)
const mcversion = mcData.version
2018-08-03 15:11:33 -04:00
const hideErrors = options.hideErrors || false
2018-08-03 15:11:33 -04:00
const server = new Server(mcversion.minecraftVersion, customPackets, hideErrors)
server.mcversion = mcversion
server.motd = motd
server.maxPlayers = maxPlayers
server.playerCount = 0
2021-08-23 14:46:45 -04:00
server.onlineModeExceptions = Object.create(null)
server.favicon = favicon
2021-09-18 17:06:20 -04:00
// The RSA keypair can take some time to generate
// and is only needed for online-mode
// So we generate it lazily when needed
Object.defineProperty(server, 'serverKey', {
configurable: true,
get () {
this.serverKey = new NodeRSA({ b: 1024 })
return this.serverKey
},
set (value) {
delete this.serverKey
this.serverKey = value
}
})
server.on('connection', function (client) {
plugins.forEach(plugin => plugin(client, server, options))
})
server.listen(port, host)
return server
}