-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketinput.cs
122 lines (102 loc) · 2.96 KB
/
socketinput.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
121
122
u using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class socketinput : MonoBehaviour
{
public static string IP = "";
Thread ReceiveThread;
public int Port;
public bool usePort;
public string debug = "";
bool useSocket;
// n Array wär mir ja lieber aber erstmal single input wär ja auch schon was.
public List<Color> DataOut;
UdpClient client;
IPEndPoint endpoint;
byte[] DataIn = new byte[1500];
//da war doch irgendwas mit 12 byte oder so.. keine Ahnung..
List<Color> BytetoColor(byte[] bytes)
{
List<Color> collist = new List<Color>();
if (bytes == null) return collist;
if (bytes.Length % 3 == 0 && bytes.Length > 2)
{
for (int i = 0; i < bytes.Length; i = i + 3)
{
Color col = new Color();
col.r = bytes[i] / 255.0f;
col.g = bytes[i + 1];
col.b = bytes[i + 2];
col.a = 1.0f;
collist.Add(col);
}
debug = "";
}
else debug = ("bytebuffer corrupt. Length Mod 3 not 0.");
return collist;
}
// Use this for initialization
void Start()
{
usePort = false;
useSocket = false;
DataOut = new List<Color>();
}
public void ListenToPort()
{
if (ReceiveThread != null)
{
ReceiveThread.Abort();
ReceiveThread = null;
}
ReceiveThread = new Thread(
new ThreadStart(ReceiveData));
ReceiveThread.IsBackground = true;
ReceiveThread.Start();
}
private void ReceiveData()
{
client = new UdpClient(Port);
while (true)
{
try
{
// Bytes empfangen.
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
int len = 0;
//Jan is klug :)
while (len < DataIn.Length)
{
byte[] pkt = client.Receive(ref anyIP);
pkt.CopyTo(DataIn, len);
len += pkt.Length;
}
}
catch (Exception e)
{
print(e.ToString());
debug = e.Message + " PortInput was: " + Port.ToString();
}
}
}
// Update is called once per frame
void Update()
{
if (null != DataIn && DataIn.Length > 0) DataOut = BytetoColor(DataIn);
}
void OnApplicationQuit()
{
if (ReceiveThread != null)
{
Debug.Log("Killed Thread " + ReceiveThread.GetHashCode().ToString());
ReceiveThread.Abort();
ReceiveThread = null;
}
}
}