aboutsummaryrefslogtreecommitdiffstats
path: root/src/server
diff options
context:
space:
mode:
Diffstat (limited to 'src/server')
-rw-r--r--src/server/Main.hx21
-rw-r--r--src/server/Utils.hx24
2 files changed, 43 insertions, 2 deletions
diff --git a/src/server/Main.hx b/src/server/Main.hx
index 8a5f381..07f782a 100644
--- a/src/server/Main.hx
+++ b/src/server/Main.hx
@@ -31,10 +31,10 @@ class Main {
public final logsDir:String;
final verbose:Bool;
final statePath:String;
- final wss:WSServer;
+ var wss:WSServer;
final localIp:String;
var globalIp:String;
- final port:Int;
+ var port:Int;
public final config:Config;
final userList:UserList;
final clients:Array<Client> = [];
@@ -85,6 +85,23 @@ class Main {
final envPort = (process.env : Dynamic).PORT;
if (envPort != null) port = envPort;
+ var attempts = 5;
+ function preparePort():Void {
+ Utils.isPortFree(port, free -> {
+ if (!free && attempts > 0) {
+ trace('Warning: port $port is already in use. Changed to ${port + 1}');
+ attempts--;
+ port++;
+ preparePort();
+ return;
+ }
+ runServer();
+ });
+ }
+ preparePort();
+ }
+
+ function runServer():Void {
trace('Local: http://$localIp:$port');
Utils.getGlobalIp(ip -> {
globalIp = ip;
diff --git a/src/server/Utils.hx b/src/server/Utils.hx
index 4e2fc9d..bab6300 100644
--- a/src/server/Utils.hx
+++ b/src/server/Utils.hx
@@ -2,6 +2,7 @@ package server;
import js.node.url.URL;
import js.node.Https;
+import js.node.Http;
import js.node.Os;
import sys.FileSystem;
@@ -11,6 +12,29 @@ class Utils {
if (!FileSystem.exists(path)) FileSystem.createDirectory(path);
}
+ public static function isPortFree(port:Int, callback:(free:Bool)->Void):Void {
+ final server = Http.createServer();
+ final timeout = 1000;
+ var status = false;
+
+ server.setTimeout(timeout);
+ server.once("error", function(err) {
+ status = false;
+ server.close();
+ });
+ server.once("timeout", function () {
+ status = false;
+ trace('Timeout (${timeout}ms) occurred waiting for port $port to be available');
+ server.close();
+ });
+ server.once("listening", function() {
+ status = true;
+ server.close();
+ });
+ server.once("close", () -> callback(status));
+ server.listen(port);
+ }
+
public static function getGlobalIp(callback:(ip:String)->Void):Void {
function onError(e):Void {
trace("Warning: connection error, server is local.");
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage