从Unity中的无线IMU应用程序接收UDP数据包

时间:2018-10-10 05:31:37

标签: c# android unity3d udp gyroscope

我有一个项目,其中我的Android手机上有一个wireless IMU应用程序。根据应用程序的描述,它以CSV格式将accel / gyro数据通过UDP发送到目标IP地址和端口。

当前,我正在尝试在Unity中编写一个接收该数据的UDPListener。

using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;


public class UDPReceiver1 : MonoBehaviour
{
Thread udpListeningThread;
public int portNumberReceive;
UdpClient receivingUdpClient;
string[] delimiters = { ", ", "," };
string[] data;

void Start()
{
    initListenerThread();
}

void initListenerThread()
{
    Debug.Log("Started on : " + portNumberReceive.ToString());
    udpListeningThread = new Thread(new ThreadStart(UdpListener));

    // Run in background
    udpListeningThread.IsBackground = true;
    udpListeningThread.Start();
}

public void UdpListener()
{
    receivingUdpClient = new UdpClient(portNumberReceive);

    while (true)
    {
        //Listening 
        try
        {
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            // Blocks until a message returns on this socket from a remote host.
            byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

            if (receiveBytes != null)
            {
                string returnData = Encoding.UTF8.GetString(receiveBytes);
                Debug.Log("Message Received" + returnData.ToString());
                Debug.Log("Address IP Sender" + RemoteIpEndPoint.Address.ToString());
                Debug.Log("Port Number Sender" + RemoteIpEndPoint.Port.ToString());

                data = returnData.Split(delimiters, StringSplitOptions.None);
                Debug.Log(data);
            }
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }
}

void OnDisable()
{
    if (udpListeningThread != null && udpListeningThread.IsAlive)
    {
        udpListeningThread.Abort();
    }

    receivingUdpClient.Close();
}
}

到目前为止,此代码根本不起作用,而我对为什么它不起作用感到非常困惑。许多论坛似乎遵循相同的结构,并且代码似乎合乎逻辑。

当我测试连接时,我所做的就是将该脚本附加到游戏对象上,设置一个任意端口号,例如“ 12345”,然后播放。同时,我在Android手机上运行了该应用程序,目标IP地址是计算机的IP地址,目标端口号是我之前使用的相同端口号。

如果有任何一种灵魂可以帮助我,我将非常感激,因为我被困在这里将近2周;(

0 个答案:

没有答案