//Start Server public void Start() { UIConsoleManager.WriteLineInYellow("Starting UDP game server..."); running = true; mainThread.Start(); }
//On finish application private void OnProcessExit(object sender, EventArgs e) { running = false; if (mainThread != null) { mainThread.Abort(); } UIConsoleManager.WriteLineInRed("Server stopped"); }
//Handle the datagram from the players private void HandleDatagram(ServerData data) { Payload payload = DataSerializer.DeserializePayload(data.datagram); short code = payload.code; try { if (payload != null && actionToTake != null) { actionToTake[code](data); } } catch (Exception e) { UIConsoleManager.WriteLineInRed(e.Message); } }
//Main thread that keeps waiting/handling players data private void MainThread() { try { UIConsoleManager.WriteLineInGreen("Server has started..."); ServerData data = null; while (running) { data = new ServerData(); data.endPoint = new IPEndPoint(IPAddress.Any, 0); data.datagram = listener.Receive(ref data.endPoint); HandleDatagram(data); } } catch (System.Exception e) { UIConsoleManager.WriteLineInRed(e.Message); } }
public void AddPlayer(Player p) { if (!isReady) { if (p1 == null) { UIConsoleManager.WriteLineInGreen("Player 1 -> {0} has joined Game {1}", p.endPoint.ToString(), index); p1 = p; } else if (p2 == null && p.clientID != p1.clientID) { UIConsoleManager.WriteLineInGreen("Player 2 -> {0} has joined Game {1}", p.endPoint.ToString(), index); p2 = p; } if (p1 != null && p2 != null) { UIConsoleManager.WriteLineInCyan("\n>>Game {0}: started running", index); isReady = true; } } }
public MultiplayerGame(int index) { this.index = index; UIConsoleManager.WriteLineInCyan("\n>>Game {0}: created", index); }