Server.cs 2.74 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;
using System.Text;
using System.Threading;

public class Server {

	TcpClient client;
	NetworkStream stream;
	TcpListener server;
	Semaphore serverSemaphore;
	PlayerManager inspector;
	Int32 port = 5555;

	public Server(Semaphore ss, PlayerManager inspec){
		serverSemaphore = ss;
		inspector = inspec;
	} // constructor

	public void startServer(){
		try{
			IPAddress localAddr = IPAddress.Parse("0.0.0.0");
			server = new TcpListener (localAddr, port);
			server.Start(); // Starts listening for incoming connection requests.
			client = server.AcceptTcpClient(); // Accepts a pending connection request.
			stream = client.GetStream();

			serverSemaphore.Release(); // Releases InspectorScript.Start() [Connection]
			getPTSFromCore();
		}

		catch(SocketException e){
			Debug.Log(e);
			closeConnections();
			Application.Quit();
		}
		catch(IOException e){
			Debug.Log(e);
			closeConnections();
			Application.Quit();
		}
		catch(Exception e){
			Debug.Log(e);
			closeConnections();
			Application.Quit();
		}
	} // startServer

	// Receives glosa and pts from Core
	void getPTSFromCore()
    {
		try
		{
			Byte[] bytes = new Byte[1024];
			String data = null;
			int i;
			Byte[] sendToCore;

			Debug.Log("getPTSFromCore");

			while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
			{
				data = System.Text.UTF8Encoding.UTF8.GetString(bytes, 0, i);
				
				sendToCore = System.Text.UTF8Encoding.UTF8.GetBytes("OK\0"); // allows Core to send next stream
				stream.Write(sendToCore, 0, sendToCore.Length);
				
				Debug.Log(data);

				if ( ! data.Equals("FINALIZE"))
					inspector.playMessage(data);
			}

			Debug.Log("~~ getPTSFromCore");
		}
		catch (Exception e)
		{
			throw new Exception(e.Source);
		}
	} // getPTSFromCore

	public void sendFinalizeToCore(){
		Byte[] sendToCore = System.Text.UTF8Encoding.UTF8.GetBytes("FINALIZE\0"); // ativar para o core
		stream.Write(sendToCore, 0, sendToCore.Length);
	}
	public void closeConnections(){

        try {
			client.Close();
			stream.Close();
			server.Stop();
		}
		catch(SocketException e){
			Debug.Log(e);
			closeConnections();
		}
		catch(IOException e){
			Debug.Log(e);
			closeConnections();
		}
	} // closeConnections

}