Unity and UDP

We need to communicate between two exes’ in two different systems using UDPClient. Both the systems are connected on ethernet.

Please help how to organize server and client combing both unity and UDPClient. Have tried many tutorials and scripts available online. Nothing seems to work out. Please help me and share the code if you have any

what is the issue/error in those tests? Cannot connect or something else?

i’ve had success with those scripts from google searches like: unity udp async
or just regular: c# simple udp async

1 Like

I could receive the message (receiver code is given below) in unity using UDP from other source but I am unable to send any messages from my form I created in unity

public class TestingUDP : MonoBehaviour
{
// Start is called before the first frame update
UdpClient client;
Thread UdpThread;
IPEndPoint anyIP;
public string text;

void Start()
{
client = new UdpClient(12345);
anyIP = new IPEndPoint(IPAddress.Any, 0);
UdpThread = new Thread(new ThreadStart(ThreadMethod));
UdpThread.Start();

}
// Update is called once per frame
void Update()
{
}
private void ThreadMethod()
{
while (true)
{
try
{
byte[ ] data = client.Receive(ref anyIP);
//Debug.Log(anyIP);
string textdata = Encoding.UTF8.GetString(data);
//string[ ] textarray = textdata.Split(‘#’);
//text = textarray[5];
text = textdata;
Debug.Log(text);
}
catch { }
}
}
private void OnApplicationQuit()
{
UdpThread.Abort();
}

whats the error/issue for sending? and how does your script look like?

also better look for udp async examples, so it doesn’t completely lock one thread.

ps. can embed scripts to forum posts with Using code tags properly

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class UDPManager : MonoBehaviour
{

    // Start is called before the first frame update
    UdpClient client;
    Thread UdpThread;
    IPEndPoint currentIP;
    public string testMessage = "test";
    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPAddress address;
    int port = 12345;
    
    void Start()
    {

        address = IPAddress.Parse("192.168.1.9");
        currentIP = new IPEndPoint(address, port);
        UdpThread = new Thread(new ThreadStart(ThreadMethod));
        UdpThread.Start();

    }

    // Update is called once per frame
    void Update()
    {

    }
    private void ThreadMethod()
    {
        while (true)
        {
           
            s.Bind(currentIP);
            byte[] data = Encoding.UTF8.GetBytes(testMessage);
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 0);
            s.SendTo(data, data.Length, SocketFlags.None, ep);
            Debug.Log(testMessage);           
        }
    }
    private void OnApplicationQuit()
    {
        UdpThread.Abort();
        s.Close();
    }
}

This is the script I attached for sending messages

SocketException: The requested address is not valid in its context.
This is the error I am getting

You should try actually connecting to the host, and seeing if you get any errors. The way you are using UDPClient is really weird.

I suggest reading up on how to use UDPClient and looking at examples of usage on something like msdn https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.udpclient?view=net-6.0

Thanks for the response
Please let me know where exactly I am doing mistake

We don’t have a host here, systems are not connected to internet. Both the systems are connected with a LAN cable and one acts as server and the other as client

They’re both on the same local network yes? Both machines need a local ip address and need to be on the same local network.

Both computers have to have a port open to receive a message, usually you’d have a listening port and send on a different one.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

using System.Threading;
public class UDPListener : MonoBehaviour
{
    private const int listenPort = 11000;
    UdpClient listener = new UdpClient(listenPort);
    IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
    void Start()
    {
        Thread thread = new Thread(Receive);
        thread.Start();
    }

    private void Receive()
    {
        try
        {
            while (true)
            {
                print("Waiting for broadcast");
                byte[] bytes = listener.Receive(ref groupEP);

                print($"Received broadcast from {groupEP} :");
                print($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");

            }
        }
        catch (SocketException e)
        {
            print(e);
        }
    }
    private void OnDestroy()
    {
        listener.Close();
    }
}

And to test

using System.Net.Sockets;
using System.Net;
using System;
using System.Text;

public class UDPClient : MonoBehaviour
{
    IEnumerator Start()
    {
        yield return new WaitForSeconds(1);
        Send("test test test");
    }
    private void Send(string msg)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        IPAddress targetAddress = IPAddress.Parse("127.0.0.1");

        byte[] sendbuf = Encoding.ASCII.GetBytes(msg);
        IPEndPoint ep = new IPEndPoint(targetAddress, 11000);

        s.SendTo(sendbuf, ep); s.Close();

        print("Message sent");
    }
}

Works on the same machine if you drag both scripts onto an object and press play. Change the ip to your target machine’s local ip address

2 Likes

You code does not run.[

UdpClient listener = new UdpClient(listenPort);
→ IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

On the new IPEndPoint(…) line, I get:
System.Net.Socket.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted at System.Net.Sockets.Socket.Bind(System.Net.EndPoint localEP).

A bit late reply but if you move “listener = new UdpClient(listenPort);” to Start function, then it works well. @lmbarns thank you for the code, saved my day, was stuck in threads instead of ol’ good enumerators :')

Unity Distribution Portal has been deprecated. For more information, see: UDP (Unity Distribution Portal) Has Been Deprecated