I want to read UDP Packages into Unity3d using Sockets. The UDP Packages are sent by another C# App, which is not a Unity App. Therefore, I attach the following script ( original source ) to one of my game objects. Unfortunately, when I run my project, Unity freezes. Can anyone 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
{
// read Thread
Thread readThread;
// udpclient object
UdpClient client;
// port number
public int port = 9900;
// UDP packet store
public string lastReceivedPacket = "";
public string allReceivedPackets = ""; // this one has to be cleaned up from time to time
// start from unity3d
void Start()
{
// create thread for reading UDP messages
readThread = new Thread(new ThreadStart(ReceiveData));
readThread.IsBackground = true;
readThread.Start();
}
// Unity Update Function
void Update()
{
// check button "s" to abort the read-thread
if (Input.GetKeyDown("q"))
stopThread();
}
// Unity Application Quit Function
void OnApplicationQuit()
{
stopThread();
}
// Stop reading UDP messages
private void stopThread()
{
if (readThread.IsAlive)
{
readThread.Abort();
}
client.Close();
}
// receive thread function
private void ReceiveData()
{
client = new UdpClient(port);
while (true)
{
try
{
// receive bytes
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
// encode UTF8-coded bytes to text format
string text = Encoding.UTF8.GetString(data);
// show received message
print(">> " + text);
// store new massage as latest message
lastReceivedPacket = text;
// update received messages
allReceivedPackets = allReceivedPackets + text;
}
catch (Exception err)
{
print(err.ToString());
}
}
}
// return the latest message
public string getLatestPacket()
{
allReceivedPackets = "";
return lastReceivedPacket;
}
}
Note: I want to use IPC to connect our game logic with Unity (using unity as nothing but a rendering engine). The C# application contains the game logic. The data that I need to transfer comprises all possible control states, such as position/orientation of different players/objects etc. Both applications are running on the same machine.
Your Receive is blocking by default - so the Update call is waiting on Receive to complete.
Add this after you create your client:
client.Client.Blocking = false;
添加接收超时
client.Client.ReceiveTimeout = 1000;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.