quakeball/Assets/Scripts/Net/NetChaperone.cs

79 lines
2.5 KiB
C#
Raw Normal View History

using System.Collections.Generic;
2020-08-07 00:57:40 +02:00
using System;
using UnityEngine;
2020-08-07 00:57:40 +02:00
using NeonTea.Quakeball.Interface;
using NeonTea.Quakeball.TeaNet.Peers;
namespace NeonTea.Quakeball.Net {
public class NetChaperone : MonoBehaviour, PeerMessageListener {
private Terminal Terminal;
private Queue<string> MessageQueue = new Queue<string>();
2020-08-07 00:57:40 +02:00
private void Start() {
if (Terminal.Singleton != null) {
Terminal = Terminal.Singleton;
Terminal.RegisterCommand("host", Host, "host [<port>] [<address>] - Hosts server at given address and port.");
Terminal.RegisterCommand("join", Join, "join [<address>] [<port>] - Tries to join a server at given address and port.");
}
}
private void Update() {
if (Terminal != null && Terminal.isActiveAndEnabled) {
while (MessageQueue.Count > 0) {
Terminal.Println(MessageQueue.Dequeue());
}
2020-08-07 00:57:40 +02:00
}
}
private bool Host(string[] args) {
if (args.Length > 2) {
Terminal.Println($"<color={Terminal.ERROR_COLOR}>Can't accept more than 2 arguments.</color>");
2020-08-07 00:57:40 +02:00
return false;
}
string addr = "0.0.0.0";
string portstr = "8080";
if (args.Length > 0) {
2020-08-07 00:57:40 +02:00
portstr = args[0];
}
if (args.Length > 1) {
addr = args[1];
}
int port;
if (!Int32.TryParse(portstr, out port)) {
return false;
}
Net.Singleton.StartServer(addr, port, this);
return true;
}
private bool Join(string[] args) {
if (args.Length > 2) {
Terminal.Println($"<color={Terminal.ERROR_COLOR}>Can't accept more than 2 arguments.</color>");
return false;
}
string addr = "127.0.0.1";
string portstr = "8080";
if (args.Length > 0) {
2020-08-07 00:57:40 +02:00
addr = args[0];
}
if (args.Length > 1) {
2020-08-07 00:57:40 +02:00
portstr = args[1];
}
int port;
if (!Int32.TryParse(portstr, out port)) {
return false;
}
Net.Singleton.StartClient(addr, port, this);
2020-08-07 00:57:40 +02:00
return true;
}
public void Message(string msg) {
MessageQueue.Enqueue(msg);
2020-08-07 00:57:40 +02:00
}
public void Err(string err) { }
}
}