(UDP Server[with multiple clients] and Client)

Can someone help me out here?
I need to make it so that the host has multiple clients on it and to answer packets by sending them back to the clients.
This is what I have so far…:
HOST

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Networking
using System.Net;
using System.Net.Sockets;

//Encoding
using System;
using System.Text;

using System.Threading;

public class UdpHost : MonoBehaviour
{

    public int port = 28500;
    Thread st;


    // Start is called before the first frame update
    void Start()
    {
  
        //Runs the function in background
        st = new Thread(StartListener);
        st.Start();
  
    }

    void StartListener()
    {
        //listen on port
        UdpClient listener = new UdpClient(port);

        //Client's IP
        IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);

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

            print("Received broadcast from " + groupEP);
            print(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
      
            //listener.Close();
        }
        catch (Exception e)
        {
            print("There is an error: "  + e.Message);
        }
        

    }



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

The client has a BUTTON to trigger the function
CLIENT

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

using System.IO;

//Encoding
using System;
using System.Text;

public class udpclientx : MonoBehaviour
{
    public string ip = "127.0.0.1";
    public int port = 28500;


    // Start is called before the first frame update
    void Start()
    {
  
    }

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

    public void ClientConnect()
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        IPAddress broadcast = IPAddress.Parse(ip);

        byte[] sendbuf = Encoding.ASCII.GetBytes("THIS IS A MESSAGE FROM CLIENT!");
        IPEndPoint ep = new IPEndPoint(broadcast, port);

        s.SendTo(sendbuf, ep);

        print("Message Sent to the broadcast address");

    }

}

Do you have a specific question, or you just want someone to do it for you?

I will say I don’t understand why on line 54 you’re starting the thread again… from inside the thread.

Also, doing network stuff on the main thread in the Client script is a bad idea.

I just wanted to make something simple, something like a chatbox, but with UDP and multiple clients with 1 server.
I achieved it on tcp, but tcp is not what I want when it comes to gaming.
From something as simple as that, I can continue; the point is, i dont know how to make it with udp. This is as far as I went with udp

P.S.
I corrected that part on line 54, it is removed… it is not needed, i forgot to remove it after testing something

Just remember UDP carries no guarantee that messages will be delivered nor that they will be delivered in any specific order. So it may not be the best protocol for a chat box, but that’s up to you.

From here I’d say:

Get your server code running inside a loop so it can keep processing new messages from clients
Get your client code to use a different thread to send messages from than the main thread.

My problem is this:
2 clients send me 2 messages, now i want to answer each of them with only 1 message(2 in total).
And let us say that the 2nd client sends me another 2 messages and i want to answer both of them.(4 in total)
client 1 = 1 message
client 2 = 3 messages

Yep, you need your server to continually listen in a loop so that it can process multiple messages.

1 Like

The way I approach this is to take a step back and create a concept of different client connections. When a message comes in it gets associated with the specific connection. Since UDP is a connectionless protocol, you have to basically create the concept of connections yourself. Then when a message arrives, you associate it with the connection, and the connection has the information needed in order to respond back to where it came from.

So if you did as I suggest, it doesn’t matter how many messages come in from whom. A message comes in, it gets associated with its connection which has the info needed to respond back to the client if necessary. You decide it is a message which needs a response, so you send the response to the client based on which client sent the message. You could have 100 clients sending 1k messages each or 2 clients sending 4 total messages, doesn’t matter cause it works the same.

As also mentioned UDP is an unreliable protocol, so if these are messages which must arrive then you’ll need to create your own reliability layer. Doing so isn’t that difficult though. In its simplest form you just take all reliable outbound messages and throw them in a list as soon as they are sent. On the receiving end, when you receive a reliable message you respond with an acknowledgement message. On the sending end when you receive an acknowledgement message you remove the original message from the list, but if you haven’t received an acknowledgement before a timeout, like 1 second, you simply resend the message. Assign message ID’s to all messages so you can do this kind of tracking, which are also useful for verifying you aren’t receiving duplicates when an acknowledgement message ends up being lost, and they are also useful if you want to enforce message ordering.

2 Likes

Okay, i will try something else. It is lots of work. Thanks anyways.

I have found better tutorials in making it multiplayer:

I did not knew of these ones before

The youtube link is outdated, does anyone have something similar that works? I don’t have that shitty ass NETWORK MANAGER.

Photon PUN2 or Mirror are options.

1 Like

If it is networking, it is not simple. Good luck!

2 Likes

Alternatively save yourself the trouble of writing a (reliable) UDP server from scratch and use something like GitHub - nxrighthere/ENet-CSharp: Reliable UDP networking library

Can someone give me a good MIRROR TUTORIAL link that explains it all; somewhere to learn from? Also is it worth working on mirror?