Example #1
0
        public void Listen(int port = DEFAULT_PORT)
        {
            udp = new UdpClient(port);

            IPEndPoint local = new IPEndPoint(IPAddress.Any, port);

            emitter.Run();
            udp.Client.SendTimeout = UDP_TIMEOUT;

            while (run)
            {
                byte[] clientMessage = null;

                try {
                    clientMessage = udp.Receive(ref local);
                } catch (SocketException) {
                    continue;
                }

                Thread task = new Thread(() => {
                    Request request = null;

                    try {
                        request = Request.FromArray(clientMessage);
                        emitter.Schedule(() => {
                            RequestedEventHandler handler = OnRequested;
                            if (handler != null)
                            {
                                handler(request);
                            }
                        });

                        IResponse response = ResolveLocal(request);

                        emitter.Schedule(() => {
                            RespondedEventHandler handler = Responded;
                            if (handler != null)
                            {
                                handler(request, response);
                            }
                        });
                        udp.Send(response.ToArray(), response.Size, local);
                    }
                    catch (SocketException) {}
                    catch (ArgumentException) {}
                    catch (ResponseException e) {
                        IResponse response = e.Response;

                        if (response == null)
                        {
                            response = Response.FromRequest(request);
                        }

                        udp.Send(response.ToArray(), response.Size, local);
                    }
                });

                task.Start();
            }
        }
Example #2
0
        protected virtual void OnResponded(IRequest request, IResponse response)
        {
            RespondedEventHandler handlers = Responded;

            if (handlers != null)
            {
                handlers(request, response);
            }
        }