I want to read UDP packets in Unity3d using Sockets. UDP packets are sent by another C # application that is not a Unity App. So I am attaching the following script ( source ) to one of my game objects. Unfortunately, when I run my project, Unity freezes. Can someone tell me why?
using UnityEngine;
using System.Collections;
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class InputUDP : MonoBehaviour
{
Thread readThread;
UdpClient client;
public int port = 9900;
public string lastReceivedPacket = "";
public string allReceivedPackets = "";
void Start()
{
readThread = new Thread(new ThreadStart(ReceiveData));
readThread.IsBackground = true;
readThread.Start();
}
void Update()
{
if (Input.GetKeyDown("q"))
stopThread();
}
void OnApplicationQuit()
{
stopThread();
}
private void stopThread()
{
if (readThread.IsAlive)
{
readThread.Abort();
}
client.Close();
}
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
print(">> " + text);
lastReceivedPacket = text;
allReceivedPackets = allReceivedPackets + text;
}
catch (Exception err)
{
print(err.ToString());
}
}
}
public string getLatestPacket()
{
allReceivedPackets = "";
return lastReceivedPacket;
}
}
Note. I want to use IPC to connect our game logic to Unity (using unity as nothing more than a rendering engine). The C # application contains the logic of the game. The data I need to transfer includes all possible control states, such as the position / orientation of different players / objects, etc. Both applications run on the same computer.