Skip to content

Instantly share code, notes, and snippets.

@MerliMejia
Created March 27, 2019 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MerliMejia/b2e127fe31d0eae7cf42ac2ea5086554 to your computer and use it in GitHub Desktop.
Save MerliMejia/b2e127fe31d0eae7cf42ac2ea5086554 to your computer and use it in GitHub Desktop.
Esta clase es la encargada de toda la comunicación cliente-servidor de parte del cliente
///<summary>
///Hecho por Merli Mejia(JAVARD) - merlimejia2@gmail.com
///
/// Esta clase es la encargada de toda la comunicacion cliente-servidor de parte del cliente
///
/// </summary>
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class networking : MonoBehaviour
{
TcpClient tcp = new TcpClient();//Intancia de cliente tcp principal
private int puerto = 8080;//puerto al que nos conectamos
private string ip = "192.168.0.5";//ip a la que nos conectamos
private int tiempoLimiteConexion = 5000;//tiempo limite para conectarse
private int memoriaParaLectura = 256;//memoria maxima de lectura
NetworkStream networkStream;//stream de servidor-cliente
Task leyendo;//nos damos cuenta cuando una lectura esta pasando, paso o no
Task escribiendo;//nos damos cuenta cuando una escritura esta pasando, paso o no
//Variables publicas**************************************************************
public string ADIVINADOR = "jugador-adivinador";
public string APOSTADOR = "jugador-apostador";
public string tipoJugador = "";
public bool conectado = false;
public bool buscandoPartida = false;
public bool enPartida = false;
//********************************************************************************
//testing***************************************************
public GameObject testing;
public string comandoEnUso = "";
//**********************************************************
void Start()
{
try
{
conectar((bool resultado) =>
{
if (resultado == true)
{
//Debug.Log("CONECTADO!");
try
{
networkStream = tcp.GetStream();
}
catch (SocketException e)
{
Debug.Log("ERROR: " + e);
}
Thread thread = new Thread(oirDelServidor);
thread.IsBackground = true;
thread.Start();
}
else
{
//Debug.Log("NO CONECTADO: ERROR DESPUES DE: " + tiempoLimiteConexion + " MS");
}
});
}
catch(SocketException e)
{
Debug.Log("ERROR: " + e);
}
}
void Update()
{
conectado = tcp.Connected;
if(conectado == true)
{
//Debug.Log(escribiendo.IsCompleted);
}
}
private void OnApplicationQuit()
{
desconectar();
}
public void desconectar()
{
networkStream.Close();
tcp.Close();
}
/// <summary>
/// Este metodo es el encargado de conectar el cliente con el servidor
/// </summary>
/// <param name="callback">Se utiliza para invocar una accion despues de que se haya conectado al servidor</param>
public void conectar(Action<bool> callback)
{
try
{
bool result = tcp.ConnectAsync(ip, puerto).Wait(tiempoLimiteConexion);
if (callback != null) callback(result);
}
catch(SocketException e)
{
Debug.Log("ERROR: " + e);
}
}
/// <summary>
/// Este metodo manda un mensaje al servidor diciendo que quiere buscar una partida
/// </summary>
public void buscarPartida()
{
buscandoPartida = true;
byte[] data = Encoding.ASCII.GetBytes("mm");
escribiendo = networkStream.WriteAsync(data, 0, data.Length);
}
/// <summary>
/// Este es el loop principal o "listener" por donde entran todos los mensajes del servidor
/// </summary>
public void oirDelServidor()
{
while (true)
{
Byte[] data = new Byte[memoriaParaLectura];
if (tcp.ReceiveBufferSize > 0)
{
networkStream.Read(data, 0, data.Length);
string mensaje = Encoding.UTF8.GetString(data);
mensaje = serializarMsj(mensaje);
ejecutarComandoServidor(mensaje);
}
}
}
private string serializarMsj(string msj)
{
List<char> cap = new List<char>();
for (int i = 0; i < msj.Length; i++)
{
if (msj[i] != '\0')
{
//Debug.Log(mensaje[i]);
cap.Add(msj[i]);
}
}
string mensaje = new string(cap.ToArray());
return mensaje;
}
/// <summary>
/// Este metodo ejecuta los comandos que le pases
/// </summary>
/// <param name="comando">Comando a ejecutar</param>
private void ejecutarComandoServidor(string comando)
{
Debug.Log(comando);
comandoEnUso = comando;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment