Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Server-Sent Events with Unity Web Request

Discussion in 'Multiplayer' started by danwillm, Jun 18, 2020.

  1. danwillm

    danwillm

    Joined:
    Jun 18, 2020
    Posts:
    1
    Hello,

    I'm trying to get a Server-Sent Event working with Unity, but with little luck. So far, this is the code that I have to try and get it to constantly listen for updates with:

    Code (CSharp):
    1.  
    2. public IEnumerator ListenForChanges(string uri)
    3.     {
    4.         UnityWebRequest req = UnityWebRequest.Get(uri);
    5.         req.SetRequestHeader("Accept", "text/event-stream");
    6.         var response = req.SendWebRequest();
    7.         while (!req.isDone)
    8.         {
    9.             Debug.Log("Text downloaded: " + req.downloadHandler.text);
    10.             yield return new WaitForSeconds(1);
    11.         }
    12.     }
    13.  
    But this doesn't seem to be working. I am able to get one response from the function, but after that I get no other responses. Is there any way that I am able to get this to work, so that it constantly checks for updates and is able to stream them to the game?

    I'm using Firebase Database as the back end, from where I am getting the data.

    Thank you very much in advance.
     
  2. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,644
    UWR doesn't support this nicely. After request is done, you have to do a new one.
     
  3. MrsPiggy

    MrsPiggy

    Joined:
    Jun 13, 2018
    Posts:
    154
    Using HTTP you can typically send one request and get one response back, after that the connection is closed and you need to repeat from the top.

    What you're trying to do requires a polling technique, where the client constantly sends requests to ask the server if there's any update. It's not the best approach but it can work for non real-time tasks.
    Another possibility is to use websockets instead, which open a persistent connection between client and server and allows the server side to push events at any time.

    There's no native Websocket support in Unity but it can be done via additional libraries such as websocket-sharp