Search Unity

[solved] Listen to a custom udp-socket-server with StartCoroutine() ?

Discussion in 'Scripting' started by LifeArtist, Jan 30, 2015.

  1. LifeArtist

    LifeArtist

    Joined:
    Mar 17, 2014
    Posts:
    17
    Hello,

    I've written a socket server in Python. The client I've written in c#.

    Server:
    • UDP Datagrams
    • Non-Blocking (to avoid waiting for a package)

    Server and client where working perfectly, until I've tried to integrate my client into a simple scene in Unity. I've already figured out that I can't use threads anymore to receive my data from server (Unity = not thread save).

    So my idea was to use the singleton pattern and start a coroutine (which is the whole time active) if a new packet is available (respectively if the server is sending data).Is this the right way of doing it or is it totally stupid (not efficiency ?) ?


    Or should I use threads and remove the inheritance(mono..). But then I don't know how I can send data from listenServer-thread to my main-thread (maybe by calling an event or so :S). I guess again only with a coroutine which will check a var for a change :O


    Regards,

    LifeArtist
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    The typical pattern for threaded data that has to be marshalled back to the main thread is to have the listener thread add to a list that is monitored via Update() in a MonoBehavior. This is similar to what you're proposing with a coroutine. The main difference is that if an Exception is thrown then the coroutine dies, whereas Update will continue to run every frame.
     
    LifeArtist likes this.
  3. LifeArtist

    LifeArtist

    Joined:
    Mar 17, 2014
    Posts:
    17
    Thank you for your fast response. Ah okay didn't know that with Exceptions and coroutines.

    So in theorie I have to create a List and add the listener thread and checking for changes. But how I can check for a return value or something simily.

    Maybe converting listener thread to an IEnumerator (yielding) and then Update() checks what value is inside ?

    Regards

    Edit1.: I've figured out that It can be handled with a static List. But I cant send Messages to my queue with my Listener thread <.< ... Any idea ?

    Edit2.: I'm so stupid ... forget to start the thread via Thread.Start()

    Thank you, KelsonMRK
     
    Last edited: Feb 1, 2015