-
Notifications
You must be signed in to change notification settings - Fork 28
/
ClientObject.cs
103 lines (88 loc) · 2.44 KB
/
ClientObject.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System.Collections.Concurrent;
using System.Threading;
using NetMQ;
using UnityEngine;
using NetMQ.Sockets;
public class NetMqListener
{
private readonly Thread _listenerWorker;
private bool _listenerCancelled;
public delegate void MessageDelegate(string message);
private readonly MessageDelegate _messageDelegate;
private readonly ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();
private void ListenerWork()
{
AsyncIO.ForceDotNet.Force();
using (var subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect("tcp://localhost:12345");
subSocket.Subscribe("");
while (!_listenerCancelled)
{
string frameString;
if (!subSocket.TryReceiveFrameString(out frameString)) continue;
Debug.Log(frameString);
_messageQueue.Enqueue(frameString);
}
subSocket.Close();
}
NetMQConfig.Cleanup();
}
public void Update()
{
while (!_messageQueue.IsEmpty)
{
string message;
if (_messageQueue.TryDequeue(out message))
{
_messageDelegate(message);
}
else
{
break;
}
}
}
public NetMqListener(MessageDelegate messageDelegate)
{
_messageDelegate = messageDelegate;
_listenerWorker = new Thread(ListenerWork);
}
public void Start()
{
_listenerCancelled = false;
_listenerWorker.Start();
}
public void Stop()
{
_listenerCancelled = true;
_listenerWorker.Join();
}
}
public class ClientObject : MonoBehaviour
{
private NetMqListener _netMqListener;
private void HandleMessage(string message)
{
var splittedStrings = message.Split(' ');
if (splittedStrings.Length != 3) return;
var x = float.Parse(splittedStrings[0]);
var y = float.Parse(splittedStrings[1]);
var z = float.Parse(splittedStrings[2]);
transform.position = new Vector3(x, y, z);
}
private void Start()
{
_netMqListener = new NetMqListener(HandleMessage);
_netMqListener.Start();
}
private void Update()
{
_netMqListener.Update();
}
private void OnDestroy()
{
_netMqListener.Stop();
}
}