-
Notifications
You must be signed in to change notification settings - Fork 20
/
UdpSocket.cs
120 lines (99 loc) · 3.6 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
Created by Youssef Elashry to allow two-way communication between Python3 and Unity to send and receive strings
Feel free to use this in your individual or commercial projects BUT make sure to reference me as: Two-way communication between Python 3 and Unity (C#) - Y. T. Elashry
It would be appreciated if you send me how you have used this in your projects (e.g. Machine Learning) at [email protected]
Use at your own risk
Use under the Apache License 2.0
Modified by:
Youssef Elashry 12/2020 (replaced obsolete functions and improved further - works with Python as well)
Based on older work by Sandra Fang 2016 - Unity3D to MATLAB UDP communication - [url]http://msdn.microsoft.com/de-de/library/bb979228.aspx#ID0E3BAC[/url]
*/
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
int i = 0; // DELETE THIS: Added to show sending data from Unity to Python via UDP
// 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();
}
}