我目前遇到一个非常奇怪的问题。我正在使用Unity 2017.4.2f2为Microsoft HoloLens开发应用程序。问题是我的代码运行良好,但是在我的应用程序运行很少之后,HoloLens不会再从我的python服务器接收到UDP消息。
以下是DatagramSocket连接的代码:
private HostName inetAddr;
private DatagramSocket sock;
private int inetPort;
private const int BUFFER_SIZE = 1024;
private byte[] buffer;
private async Task ConnectSocket()
{
sock = new DatagramSocket();
sock.MessageReceived += Socket_MessageReceived;
sock.Control.MulticastOnly = true;
sock.Control.InboundBufferSizeInBytes = BUFFER_SIZE;
await sock.BindServiceNameAsync(inetPort.ToString());
sock.JoinMulticastGroup(inetAddr);
// Send empty message to initialize communication
await SendWithExistingSocket("");
}
private async Task SendWithExistingSocket(string text)
{
if (sock != null)
{
Stream stream = (await sock.GetOutputStreamAsync(inetAddr, inetPort.ToString())).AsStreamForWrite();
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(text);
await writer.FlushAsync();
}
}
}
private async void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
using (Stream streamIn = args.GetDataStream().AsStreamForRead(BUFFER_SIZE))
{
await streamIn.ReadAsync(buffer, 0, BUFFER_SIZE);
}
IPAddress address = IPAddress.Parse(inetAddr.RawName);
IPEndPoint from = new IPEndPoint(address, int.Parse(sender.Information.LocalPort));
//Custom function for dealing with packet
HandlePacket(buffer, from);
}
正如我所说,这个问题很奇怪,因为这段代码实际上有效,直到HoloLens停止接收UDP数据报(函数Socket_MessageReceived未调用)。在我的示例中,inetAddr = 224.3.0.5和inetPort = 7667
重要的是,我的应用程序在从设备门户重启HoloLens后重新启动接收UDP消息 。
当我在本地计算机上部署UWP应用程序时,我没有遇到此问题。只有当我将我的应用程序部署到HoloLens时。我还有一个与UdpClient类进行通信的实现(用于在编辑器中进行测试),它的工作非常好并且不会像这样。
我已经尝试过:
任何想法为什么? 谢谢
答案 0 :(得分:0)
请勿与您的编写者和接收者一起使用Using
,因为这会终止与您的听众的交流。我遇到了这个问题,直到我这样做之前,我一直在发疯。现在它就像一种魅力。
我收到这样的包裹:
bool refresh = false;
bool sound = false;
string response;
uint stringLength = args.GetDataReader().UnconsumedBufferLength;
response = args.GetDataReader().ReadString(stringLength);
并这样编写程序包:
IOutputStream outputStream;
HostName remoteHostname = new HostName("224.3.0.5");
outputStream = await socketinstance.GetOutputStreamAsync(remoteHostname, ClientPortNumber);
DataWriter writer = new DataWriter(outputStream);
writer.WriteString(request);
await writer.StoreAsync();