-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUdpSocket.cs
104 lines (88 loc) · 2.78 KB
/
UdpSocket.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
104
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UdpSocket : MonoBehaviour
{
[HideInInspector] public bool isTxStarted = false;
[SerializeField] string IP = "127.0.0.1"; // local host
[SerializeField] int rxPort = 8000; // port to receive data from Python on
[SerializeField] int txPort = 8001; // port to send data to Python on
// Create necessary UdpClient objects
UdpClient client;
IPEndPoint remoteEndPoint;
Thread receiveThread; // Receiving Thread
IEnumerator SendDataCoroutine() // DELETE THIS: Added to show sending data from Unity to Python via UDP
{
while (true)
{
SendData("Sent from Unity: " + i.ToString());
i++;
yield return new WaitForSeconds(1f);
}
}
public void SendData(string message) // Use to send data to Python
{
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
void Awake()
{
// Create remote endpoint (to Matlab)
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), txPort);
// Create local client
client = new UdpClient(rxPort);
// local endpoint define (where messages are received)
// Create a new thread for reception of incoming messages
receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
// Initialize (seen in comments window)
print("UDP Comms Initialised");
StartCoroutine(SendDataCoroutine()); // DELETE THIS: Added to show sending data from Unity to Python via UDP
}
// Receive data, update packets received
private void ReceiveData()
{
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
string text = Encoding.UTF8.GetString(data);
print(">> " + text);
ProcessInput(text);
}
catch (Exception err)
{
print(err.ToString());
}
}
}
private void ProcessInput(string input)
{
// PROCESS INPUT RECEIVED STRING HERE
if (!isTxStarted) // First data arrived so tx started
{
isTxStarted = true;
}
}
//Prevent crashes - close clients and threads properly!
void OnDisable()
{
if (receiveThread != null)
receiveThread.Abort();
client.Close();
}
}