Exemplo n.º 1
0
        /// <summary>
        /// Main thread method
        /// </summary>
        private void ServerThread()
        {
            try
            {
                UdpState udpState = new UdpState();
                udpState.IPEndPoint = new IPEndPoint(IPAddress.Any, ListenPort);
                udpState.UdpClient  = new UdpClient(udpState.IPEndPoint);
                udpState.UdpClient.BeginReceive(new AsyncCallback(ReceiveCallback), udpState);

                // Main loop
                while (serverRunning)
                {
                }
            }
            catch (SocketException socketException)
            {
                if (OnSocketException != null)
                {
                    OnSocketException(socketException);
                    Stop();
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// AsyncCallback fro UDP receive
        /// </summary>
        /// <param name="ar">Async result</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            UdpState   udpState  = (UdpState)ar.AsyncState;
            UdpClient  udpClient = udpState.UdpClient;
            IPEndPoint endPoint  = udpState.IPEndPoint;

            byte[] data = udpClient.EndReceive(ar, ref endPoint);

            // Send the data back
            udpClient.Connect(endPoint);
            udpClient.Send(data, data.Length);
            udpClient.Close();

            // Rise the event
            if (OnDataReceived != null)
            {
                OnDataReceived(endPoint, data);
            }

            udpState.IPEndPoint = new IPEndPoint(IPAddress.Any, ListenPort);
            udpState.UdpClient  = new UdpClient(udpState.IPEndPoint);
            udpState.UdpClient.BeginReceive(new AsyncCallback(ReceiveCallback), udpState);
        }