Server.cs 2.77 KB
/**********************
********LAVID**********
*******VLibras*********
*------------------------------------------------------------------------
*Description:
*Server gets pts from Core (client) by TCP connection
*and runs the animations until a final tag is found.
*------------------------------------------------------------------------
*Author: Claudiomar Araujo # claudiomar.araujo@lavid.ufpb.br
*------------------------------------------------------------------------
***********************/

using UnityEngine;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class Server {

	public readonly string ADDRESS = "0.0.0.0";
    public readonly Int32 PORT = 5555;

	private TcpClient client;
	private NetworkStream stream;
	private TcpListener server;
	private bool isReady = false;

	private PlayerManager manager;
	
	public Server(PlayerManager manager)
	{
		this.manager = manager;

		try {
			// Starts listening for incoming connection requests
			server = new TcpListener(IPAddress.Parse(ADDRESS), PORT);
			server.Start();

			// Accepts a pending connection request
			Debug.Log("S(): Waiting client");
			client = server.AcceptTcpClient();
			stream = client.GetStream();
		}
		catch (Exception e)
		{
			Debug.Log(e);
			CloseConnections();
			manager.FinalizationLocker.Release();

			throw e;
		}
	}

	public bool IsNotReady {
		get { return !isReady; }
	}

	/**
	 *	Starts receiving of glosa and time from server.
	 *	Stops when receive "FINALIZE".
	 */
	public void StartCommunication()
    {
		Debug.Log("S.SC()");

		try
		{
			Byte[] bytes = new Byte[1024];
			int size;

			while ((size = stream.Read(bytes, 0, bytes.Length)) != 0)
			{
				String data = System.Text.UTF8Encoding.UTF8.GetString(bytes, 0, size);
				
				// Notify the core that the message was received
				Byte[] sendToCore = System.Text.UTF8Encoding.UTF8.GetBytes("OK\0");
				stream.Write(sendToCore, 0, sendToCore.Length);
				
				Message message = new Message(data);

				Debug.Log("S.SC(): Received: " + message.Text);

				if (message.Text.Equals("FINALIZE"))
				{
					isReady = true;
					break;
				}
				else manager.enqueueMessage(message);
			}

			Debug.Log("S.SC(): END");
		}
		catch (Exception e)
		{
			Debug.Log(e);

			if (!this.isReady)
			{
				CloseConnections();
				manager.FinalizationLocker.Release();
			}

			throw e;
		}
	}

	public void SendFinalizeToCore()
	{
		Byte[] sendToCore = System.Text.UTF8Encoding.UTF8.GetBytes("FINALIZE\0");
		stream.Write(sendToCore, 0, sendToCore.Length);

		CloseConnections();
    }

	private void CloseConnections()
	{
        try {
			client.Close();
			stream.Close();
			server.Stop();
		}
		catch (SocketException e) {
			Debug.Log(e);
			CloseConnections();
		}
		catch (IOException e) {
			Debug.Log(e);
			CloseConnections();
		}
	}

}