Пример #1
0
        private void Run()
        {
            //...建立接收的位置, 所有
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            //...返回對方的位置
            EndPoint remoteEP = (EndPoint)(sender);

            try
            {
                while (true)
                {
                    _allDone.Reset();
                    UDPServerStateObject stateObject = new UDPServerStateObject();
                    stateObject.workSocket    = _socket;
                    stateObject.receiveBuffer = new byte[_receiveBuffer];
                    _socket.BeginReceiveFrom(stateObject.receiveBuffer, 0, _receiveBuffer, 0, ref remoteEP, new AsyncCallback(ReceiveFromCallback), stateObject);
                    _allDone.WaitOne();
                }
            }
            catch (Exception ex)
            {
                _allDone.Set();
                KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynUDPServer>>Run", ex.Message);
            }
        }
Пример #2
0
        private void ReceiveFromCallback(IAsyncResult ar)
        {
            try
            {
                UDPServerStateObject so = (UDPServerStateObject)ar.AsyncState;
                Socket socket           = so.workSocket;

                IPEndPoint sender             = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   tempRemoteEP       = (EndPoint)sender;
                int        receivedDataLength = socket.EndReceiveFrom(ar, ref tempRemoteEP);
                so.tempRemoteEP = tempRemoteEP;

                ReceiveEvent(so);//...交由外部處理
            }
            catch (Exception ex)
            {
                KConsole.Write(ErrorLevel.Serious, "Kernel>>AsynUDPServer>>ReceiveFromCallback", ex.Message);
            }
            finally
            {
                _allDone.Set();
            }
        }