Servidor de soquete simples no Unity
Eu quero usar um plugin C # no meu projeto do Unity. Esse plug-in deve funcionar como um servidor que obterá valores de um cliente para que eu possa usar esses valores para processamento adicional. O problema é que o servidor possui um loop infinito. E loops infinitos fazem o Unity travar. Como lidar com isso?
Edição: Estou anexando um trecho de código do programa do servidor. Na minha opinião, existem 2 pontos que podem estar causando problemas. Os loops infinitos e o ponto em que o programa é suspenso, como comentado no código:
void networkCode()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1755);
// Create a TCP/IP socket.
listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
// Program is suspended while waiting for an incoming connection.
Debug.Log("HELLO"); //It works
handler = listener.Accept();
Debug.Log("HELLO"); //It doesn't work
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
System.Threading.Thread.Sleep(1);
}
System.Threading.Thread.Sleep(1);
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
EDIT: Após a ajuda do @Programmer, o plug-in C # está completo. Mas o Unity não está lendo os valores corretos. Estou anexando o código do lado do Unity:
using UnityEngine;
using System;
using SyncServerDLL; //That's our library
public class receiver : MonoBehaviour {
SynchronousSocketListener obj; //That's object to call server methods
// Use this for initialization
void Start() {
obj = new SynchronousSocketListener ();
obj.startServer ();
}
// Update is called once per frame
void Update() {
Debug.Log (obj.data);
}
}
Testei a classe SynchronousSocketListener completamente no Visual Studio. Está dando bons resultados lá.