using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using TMPro;
using UnityEngine;

public class UDPServer : MonoBehaviour
{
    public TextMeshProUGUI text;

    private Socket socket;
    private bool isServerStarted = false;   

    // Start is called before the first frame update
    void Start()
    {
        StartServer();
        StartCoroutine(Listen());   
    }

    private void StartServer()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        var localIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
        socket.Bind(localIP);
        isServerStarted = true;
        Debug.Log("Server was started.");
    }
    private IEnumerator Listen()
    {
        while (isServerStarted)
        {
            EndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = new byte[1024];
            var result = socket.ReceiveFrom(data, SocketFlags.None, ref remoteIp);
            var message = Encoding.UTF8.GetString(data, 0, result);
            string[] args = message.Split('|');
            string serverMessage = "Hello from server!";
            byte[] serverData = Encoding.UTF8.GetBytes(serverMessage);
            int bytes = socket.SendTo(serverData, remoteIp);    
            text.text = args[1];
            yield return new WaitForEndOfFrame();   
        }
    }
}
