Event Listener Creation

Coordinator
Feb 29, 2016 at 8:15 PM
nicoriff wrote:

I´m trying to create a UDPClient from javascript but I cannot find the way to add the event to the object I´ve created on the javascript side and assign a callback function. Can someone help me with some simple sample code of how I can accomplish this?

We'd love to help, but we'd need more information. What kind of object (host or script) is the event source? What kind of object is the listener? How does the listener register itself with the source (or how would you like that to happen)? What host facilities are you exposing to the script engine? Some sample code could provide the necessary context.

Thanks!
Mar 4, 2016 at 8:43 PM
Edited Mar 4, 2016 at 8:44 PM
Thanks for your reply, basically, I want to replicate this sample code on the script side. I did transported the code but I couldn´t get it to work.
    public static void ListenUDP()
    {
        _lst = new UdpClient(4567);
        var groupEp = new IPEndPoint(IPAddress.Any, 4567);          

        try
        {
            while (true)
            {
                Thread.Sleep(50);
                var receiveByteArray = _lst.Receive(ref groupEp);
                ClientIp = groupEp.Address.ToString();
                var receivedData = Encoding.ASCII.GetString(receiveByteArray, 0, receiveByteArray.Length);

                DoSomething(receivedData);
            }
        }
        catch (Exception ex)
        {
            Log.Log.LogError(ex.ToString());
        }
    }
Coordinator
Mar 5, 2016 at 4:19 AM
Hello!

Here's a JavaScript sample that works and is very similar to your C# code:
using (var engine = new V8ScriptEngine()) {
    engine.AddHostObject("host", new HostFunctions());
    engine.AddHostType(typeof(UdpClient));
    engine.AddHostType(typeof(IPEndPoint));
    engine.AddHostType(typeof(IPAddress));
    engine.AddHostType(typeof(Encoding));
    engine.AddHostType(typeof(Console));
    engine.Execute(@"
        _lst = new UdpClient(4567);
        var groupEp = host.newVar(new IPEndPoint(IPAddress.Any, 4567));
        try {
            while (true) {
                var bytes = _lst.Receive(groupEp.ref);
                Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytes.Length));
            }
        }
        catch (ex) {
            Console.WriteLine(ex.hostException);
        }
    ");
}
Good luck!
Mar 10, 2016 at 1:03 PM
Thank you for that!. The code worked just fine!. Every day happier to work with ClearScript!.