-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSonarTCPPublisher.cs
More file actions
69 lines (60 loc) · 1.8 KB
/
Copy pathSonarTCPPublisher.cs
File metadata and controls
69 lines (60 loc) · 1.8 KB
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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class SonarTcpPublisher : MonoBehaviour
{
public SonarRayCast sonarRayCast; // Inspector'dan atayın
private TcpListener tcpListener;
private Thread listenerThread;
private bool running = false;
void Start()
{
tcpListener = new TcpListener(IPAddress.Any, 5556);
tcpListener.Start();
running = true;
listenerThread = new Thread(ClientHandler);
listenerThread.IsBackground = true;
listenerThread.Start();
}
void ClientHandler()
{
while (running)
{
if (tcpListener.Pending())
{
TcpClient client = tcpListener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
while (client.Connected && running)
{
if (sonarRayCast != null)
{
float[] hits = sonarRayCast.Hits;
if (hits != null && hits.Length > 0)
{
string message = string.Join(",", hits);
byte[] data = Encoding.UTF8.GetBytes(message + "\n");
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
Thread.Sleep(100); // 10Hz
}
client.Close();
}
else
{
Thread.Sleep(100);
}
}
}
void OnDestroy()
{
running = false;
tcpListener.Stop();
if (listenerThread != null && listenerThread.IsAlive)
listenerThread.Join();
}
}