Skip to content

Instantly share code, notes, and snippets.

@RoeiRubach
Last active September 14, 2021 18:52
Show Gist options
  • Select an option

  • Save RoeiRubach/81cb3c6f7525054de4340074175a2b4f to your computer and use it in GitHub Desktop.

Select an option

Save RoeiRubach/81cb3c6f7525054de4340074175a2b4f to your computer and use it in GitHub Desktop.
[UDPManager] Simple UDP that manages sending & receiving messages #UDP
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class UDPManager
{
private UdpClient _client;
private Thread _receiveThread;
private int _portDestination;
public UDPManager(int portDestination)
{
_portDestination = portDestination;
StartConnection();
}
public void StartConnection()
{
try { _client = new UdpClient(_portDestination); }
catch (Exception error)
{
Debug.Log("Failed to listen for UDP at port " + _portDestination + ": " + error.Message);
return;
}
Debug.Log("Created receiving client at port " + _portDestination);
StartReceiveThread();
}
private void StartReceiveThread()
{
_receiveThread = new Thread(() => ListenForMessages());
_receiveThread.IsBackground = true;
_receiveThread.Start();
}
private void ListenForMessages()
{
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
Byte[] receiveBytes = _client.Receive(ref remoteIpEndPoint);
string stringData = Encoding.UTF8.GetString(receiveBytes);
}
catch (SocketException error)
{
bool isSocketClosed = error.ErrorCode != 10004;
if (isSocketClosed)
Debug.Log($"Socket exception while receiving data from udp client: {error.Message}");
}
catch (Exception error) { Debug.Log($"Error receiving data from udp client: {error.Message}"); }
// do something with your message {stringData}...
Thread.Sleep(1);
}
}
public void SendString(string message)
{
try
{
UdpClient sendClient = new UdpClient();
//string targetIP = the IP you want to send your message to;
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(targetIP), _portDestination);
byte[] data = Encoding.UTF8.GetBytes(message);
sendClient.Send(data, data.Length, endPoint);
sendClient.Close();
}
catch (Exception error) { Debug.Log(error.ToString()); }
}
public void Stop()
{
if (_receiveThread.IsAlive)
_receiveThread.Abort();
_client.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment