-
Notifications
You must be signed in to change notification settings - Fork 28
/
ServerObject.cs
93 lines (76 loc) · 2.15 KB
/
ServerObject.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
using System.Diagnostics;
using System.Threading;
using NetMQ;
using NetMQ.Sockets;
using UnityEngine;
public class NetMqPublisher
{
private readonly Thread _listenerWorker;
private bool _listenerCancelled;
public delegate string MessageDelegate(string message);
private readonly MessageDelegate _messageDelegate;
private readonly Stopwatch _contactWatch;
private const long ContactThreshold = 1000;
public bool Connected;
private void ListenerWork()
{
AsyncIO.ForceDotNet.Force();
using (var server = new ResponseSocket())
{
server.Bind("tcp://*:12346");
while (!_listenerCancelled)
{
Connected = _contactWatch.ElapsedMilliseconds < ContactThreshold;
string message;
if (!server.TryReceiveFrameString(out message)) continue;
_contactWatch.Restart();
var response = _messageDelegate(message);
server.SendFrame(response);
}
}
NetMQConfig.Cleanup();
}
public NetMqPublisher(MessageDelegate messageDelegate)
{
_messageDelegate = messageDelegate;
_contactWatch = new Stopwatch();
_contactWatch.Start();
_listenerWorker = new Thread(ListenerWork);
}
public void Start()
{
_listenerCancelled = false;
_listenerWorker.Start();
}
public void Stop()
{
_listenerCancelled = true;
_listenerWorker.Join();
}
}
public class ServerObject : MonoBehaviour
{
public bool Connected;
private NetMqPublisher _netMqPublisher;
private string _response;
private void Start()
{
_netMqPublisher = new NetMqPublisher(HandleMessage);
_netMqPublisher.Start();
}
private void Update()
{
var position = transform.position;
_response = $"{position.x} {position.y} {position.z}";
Connected = _netMqPublisher.Connected;
}
private string HandleMessage(string message)
{
// Not on main thread
return _response;
}
private void OnDestroy()
{
_netMqPublisher.Stop();
}
}