Cyber/Assets/Scripts/Networking/NetworkEstablisher.cs

86 lines
2.4 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/**
* This class is used pretty much anywhere in order to make the "first step" of networking.
* It adds the proper components to World Root and tells them to start.
* */
public class NetworkEstablisher : MonoBehaviour {
[Tooltip("Required field only if StartClient() is used.")]
public InputField IPField;
[Tooltip("Required field only if StartClient() is used.")]
2017-05-08 02:59:42 +02:00
public InputField ClientPortField;
[Tooltip("Required field only if StartServer() is used.")]
2017-05-08 02:59:42 +02:00
public InputField ServerPortField;
2017-05-08 02:59:42 +02:00
public GameObject WorldRoot;
// Use this for initialization
void Start () {
Term.AddCommand("join", "joins a server at localhost:3935", (args) => {
StartClient("localhost", 3935);
});
Term.AddCommand("join (ip)", "joins a server at given ip and port 3935", (args) => {
string ip = args[0];
StartClient(ip, 3935);
});
Term.AddCommand("join (ip) (port)", "joins a server at given ip and port", (args) => {
string ip = args[0];
int port = 3935;
int.TryParse(args[1], out port);
StartClient(ip, port);
});
Term.AddCommand("host", "host a server at port 3935", (args) => {
StartServer(3935);
});
Term.AddCommand("host (port)", "host a server at given port", (args) => {
int port = 3935;
int.TryParse(args[0], out port);
StartServer(port);
});
}
// Update is called once per frame
void Update () {
}
public void StartClient() {
2017-05-08 02:59:42 +02:00
string IP = IPField.text;
if (IP.Length == 0) {
IP = "localhost";
}
2017-05-08 02:59:42 +02:00
string PortText = ClientPortField.text;
int Port = 3935;
if (PortText.Length > 0) {
Port = Int32.Parse(PortText);
}
2017-05-08 02:59:42 +02:00
StartClient(IP, Port);
}
public void StartClient(string ip, int port) {
WorldRoot.AddComponent<Client>();
Client.Launch(ip, port);
}
public void StartServer() {
2017-05-08 02:59:42 +02:00
string PortText = ServerPortField.text;
int Port = 3935;
if (PortText.Length > 0) {
Port = Int32.Parse(PortText);
}
2017-05-08 02:59:42 +02:00
StartServer(Port);
}
public void StartServer(int port) {
WorldRoot.AddComponent<Server>();
Server.Launch(port);
}
}