Make Client and Server Singletons and add Networking docs

This commit is contained in:
Sofia 2017-05-08 22:11:05 +03:00
parent 78dfe42106
commit db87a13e7f
5 changed files with 172 additions and 25 deletions

View File

@ -3,24 +3,35 @@ using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.Networking; using UnityEngine.Networking;
/// <summary>
/// Client-class used to connecting to a server and communicating to it.
/// Also handles all events incoming from the server and forwards them where they should be handled.
/// </summary>
public class Client : MonoBehaviour { public class Client : MonoBehaviour {
NetworkClient NetClient; NetworkClient NetClient;
private bool Running = false; private bool Running = false;
private static Client Singleton;
public Client() {
Singleton = this;
}
// Use this for initialization // Use this for initialization
void Start () { void Start () {
} }
// Update is called once per frame // Update is called once per frame
void Update () { void Update () {
if (NetClient.isConnected) {
}
} }
public void LaunchClient(string ip, int port) { // Launches the client at given IP and port.
private bool LaunchClient(string ip, int port) {
if (Running) { if (Running) {
return; return false;
} }
ConnectionConfig Config = new ConnectionConfig(); ConnectionConfig Config = new ConnectionConfig();
@ -43,9 +54,13 @@ public class Client : MonoBehaviour {
Debug.Log("Client launched!"); Debug.Log("Client launched!");
Term.Println("Client launched!"); Term.Println("Client launched!");
return true;
} }
public void HandlePacket(NetworkMessage msg) { // Handles custom packets
private void HandlePacket(NetworkMessage msg) {
switch (msg.msgType) { switch (msg.msgType) {
case (PktType.TextMessage): case (PktType.TextMessage):
TextMessage TextMsg = new TextMessage(); TextMessage TextMsg = new TextMessage();
@ -59,29 +74,75 @@ public class Client : MonoBehaviour {
} }
} }
public void Send(short type, MessageBase message) { // Built-in handles for some events
NetClient.Send(type, message);
}
public void OnConnected(NetworkMessage msg) { private void OnConnected(NetworkMessage msg) {
Debug.Log("Connected!"); Debug.Log("Connected!");
Term.Println("Connected!"); Term.Println("Connected!");
Term.AddCommand("send (message)", "Send a message across the vastness of space and time!", (args) => { Term.AddCommand("send (message)", "Send a message across the vastness of space and time!", (args) => {
Term.Println("You: " + args[0]); Term.Println("You: " + args[0]);
Send(PktType.TextMessage, new TextMessage("A Client: " + args[0])); NetClient.Send(PktType.TextMessage, new TextMessage("A Client: " + args[0]));
}); });
} }
public void OnDisconnected(NetworkMessage msg) { private void OnDisconnected(NetworkMessage msg) {
Debug.Log("Disconnected!"); Debug.Log("Disconnected!");
Term.Println("Disconnected!"); Term.Println("Disconnected!");
Running = false;
} }
public void OnError(NetworkMessage msg) { private void OnError(NetworkMessage msg) {
Debug.LogError("Encountered a network error. Shutting down."); Debug.LogError("Encountered a network error. Shutting down.");
Term.Println("Encountered a network error. Shutting down."); Term.Println("Encountered a network error. Shutting down.");
NetClient.Disconnect(); NetClient.Disconnect();
Running = false; Running = false;
} }
// Static interface for usage outside of Client
/// <summary>
/// Will launch the client and attempt to connect to the server.
/// Returns false if client is already running, otherwise true.
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <returns></returns>
public static bool Launch(string ip, int port) {
return Singleton.LaunchClient(ip, port);
}
/// <summary>
/// Send messages to the server if the connection is active.
/// If client is not active, this will return false, otherwise true.
/// </summary>
/// <param name="msgType"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool Send(short msgType, MessageBase message) {
if (Singleton.Running) {
Singleton.NetClient.Send(msgType, message);
return true;
} else {
return false;
}
}
/// <summary>
/// Returns if the client is running or not.
/// This is independant weather the client is connected or not.
/// </summary>
/// <returns></returns>
public static bool isRunning() {
return Singleton.Running;
}
/// <summary>
/// Returns if the client is connected or not.
/// </summary>
/// <returns></returns>
public static bool isConnected() {
return Singleton.NetClient.isConnected;
}
} }

View File

@ -1,20 +1,42 @@
using UnityEngine.Networking; using UnityEngine.Networking;
/// <summary>
/// Generic Text Message for chat etc.
/// To be removed later when no longer necessary.
/// </summary>
public class TextMessage : MessageBase { public class TextMessage : MessageBase {
/// <summary>
/// Message inside the Text Message. Does not container sender information.
/// </summary>
public string Message; public string Message;
/// <summary>
/// Create a TextMessage containing the message to be sent.
/// </summary>
/// <param name="message"></param>
public TextMessage(string message) { public TextMessage(string message) {
this.Message = message; this.Message = message;
} }
/// <summary>
/// Parameter-less constructor using when deserializing the message.
/// </summary>
public TextMessage() { public TextMessage() {
} }
/// <summary>
/// Used to deserialize a message received via networking.
/// </summary>
/// <param name="reader"></param>
public override void Deserialize(NetworkReader reader) { public override void Deserialize(NetworkReader reader) {
Message = reader.ReadString(); Message = reader.ReadString();
} }
/// <summary>
/// Used to serialize the message before it is sent.
/// </summary>
/// <param name="writer"></param>
public override void Serialize(NetworkWriter writer) { public override void Serialize(NetworkWriter writer) {
writer.Write(Message); writer.Write(Message);
} }

View File

@ -65,8 +65,8 @@ public class NetworkEstablisher : MonoBehaviour {
} }
public void StartClient(string ip, int port) { public void StartClient(string ip, int port) {
Client Client = WorldRoot.AddComponent<Client>(); WorldRoot.AddComponent<Client>();
Client.LaunchClient(ip, port); Client.Launch(ip, port);
} }
public void StartServer() { public void StartServer() {
@ -79,7 +79,7 @@ public class NetworkEstablisher : MonoBehaviour {
} }
public void StartServer(int port) { public void StartServer(int port) {
Server Server = WorldRoot.AddComponent<Server>(); WorldRoot.AddComponent<Server>();
Server.LaunchServer(port); Server.Launch(port);
} }
} }

View File

@ -2,6 +2,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
/// <summary>
/// Types of custom created packets.
/// </summary>
public class PktType { public class PktType {
public const short TextMessage = 200; public const short TextMessage = 200;

View File

@ -5,8 +5,11 @@ using UnityEngine.Networking;
public class Server : MonoBehaviour { public class Server : MonoBehaviour {
private static Server Singleton;
// Use this for initialization // Use this for initialization
void Start () { void Start () {
Singleton = this;
} }
// Update is called once per frame // Update is called once per frame
@ -14,7 +17,10 @@ public class Server : MonoBehaviour {
} }
public void LaunchServer(int port) { private bool LaunchServer(int port) {
if (NetworkServer.active) {
return false;
}
ConnectionConfig Config = new ConnectionConfig(); ConnectionConfig Config = new ConnectionConfig();
Config.AddChannel(QosType.ReliableSequenced); Config.AddChannel(QosType.ReliableSequenced);
@ -36,9 +42,13 @@ public class Server : MonoBehaviour {
Term.Println("You: " + args[0]); Term.Println("You: " + args[0]);
SendToAll(PktType.TextMessage, new TextMessage("Server: " + args[0])); SendToAll(PktType.TextMessage, new TextMessage("Server: " + args[0]));
}); });
return true;
} }
public void HandlePacket(NetworkMessage msg) { // Custon packet handler
private void HandlePacket(NetworkMessage msg) {
switch(msg.msgType) { switch(msg.msgType) {
case PktType.TextMessage: case PktType.TextMessage:
@ -53,22 +63,73 @@ public class Server : MonoBehaviour {
} }
} }
public void SendToAll(short type, MessageBase message) { // Internal built-in event handler
NetworkServer.SendToAll(type, message);
}
public void OnConnected(NetworkMessage msg) { private void OnConnected(NetworkMessage msg) {
Debug.Log("Someone connected!"); Debug.Log("Someone connected!");
Term.Println("Someone connected!"); Term.Println("Someone connected!");
} }
public void OnDisconnected(NetworkMessage msg) { private void OnDisconnected(NetworkMessage msg) {
Debug.Log("Someone disconnected."); Debug.Log("Someone disconnected.");
Term.Println("Someone disconnected."); Term.Println("Someone disconnected.");
} }
public void OnError(NetworkMessage msg) { private void OnError(NetworkMessage msg) {
Debug.LogError("Encountered a network error on server"); Debug.LogError("Encountered a network error on server");
Term.Println("Encountered a network error on server"); Term.Println("Encountered a network error on server");
} }
// Static methods for public usage
/// <summary>
/// Launches the server if not already launched.
/// Returns false if the server was already launched, true otherwise.
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
public static bool Launch(int port) {
return Singleton.LaunchServer(port);
}
/// <summary>
/// Attempts to send a message to all clients who are listening.
/// Returns false if server wasn't active, true otherwise.
/// </summary>
/// <param name="msgType"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool SendToAll(short msgType, MessageBase message) {
if (NetworkServer.active) {
NetworkServer.SendToAll(msgType, message);
return true;
} else {
return false;
}
}
/// <summary>
/// Attempts to send a message to a specific client.
/// Returns false if server wasn't active, true otherwise.
/// </summary>
/// <param name="clientID"></param>
/// <param name="msgType"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool Send(int clientID, short msgType, MessageBase message) {
if (NetworkServer.active) {
NetworkServer.SendToClient(clientID, msgType, message);
return true;
} else {
return false;
}
}
/// <summary>
/// Is the server currently active.
/// </summary>
/// <returns></returns>
public static bool isRunning() {
return NetworkServer.active;
}
} }