当前位置: 首页>>代码示例>>C#>>正文


C# Socket.EndReceiveFrom方法代码示例

本文整理汇总了C#中System.Net.Sockets.Socket.EndReceiveFrom方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.EndReceiveFrom方法的具体用法?C# Socket.EndReceiveFrom怎么用?C# Socket.EndReceiveFrom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.Socket的用法示例。


在下文中一共展示了Socket.EndReceiveFrom方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: StartUdpServer

        private async void StartUdpServer()
        {
            var udpListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            // Important to specify a timeout value, otherwise the socket ReceiveFrom() 
            // will block indefinitely if no packets are received and the thread will never terminate
            udpListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
            udpListener.Bind(new IPEndPoint(IPAddress.Any, 54321));

            var buffer = new byte[1500];
            EndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                var result = await Task.Factory.FromAsync(
               (iar, s) =>
                   udpListener.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref sender, iar,
                       null),
               iar => udpListener.EndReceiveFrom(iar, ref sender), null);
                if (result > 0)
                {
                    if (firstPacket == DateTime.MinValue)
                        firstPacket = DateTime.Now;

                    var data = new byte[result];
                    Buffer.BlockCopy(buffer, 0, data, 0, result);
                    ring.AddData(data);

                    Frame f = null;
                    do
                    {
                        f = ring.ReadFrame();
                        if (f != null)
                        {
                            f.Time = (DateTime.Now - firstPacket).TotalSeconds;
                            var ev = OnFrameReceived;
                            if (ev != null)
                            {
                                OnFrameReceived(this, new FrameReceivedEventArgs(f));
                            }
                        }
                    } while (f != null);

                }
            }
        }
开发者ID:kendemu,项目名称:ardrone3-pcap,代码行数:47,代码来源:BebopServer.cs

示例2: Receive

        private void Receive(Socket socket, EndPoint endPoint)
        {
            var data = new byte[socket.ReceiveBufferSize];
            socket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref endPoint, ar =>
            {
                if (DataReceived != null)
                {
                    var i = socket.EndReceiveFrom(ar, ref endPoint);
                    var data2 = new byte[i];
                    Array.Copy(data, data2, i);
                    var command = CommandBase.Parse(data2);

                    if (_debugLog != null)
                        _debugLog.WriteLine("Receive " + command.GetType().Name + "   Token: " + command.Token);

                    DataReceived(command);
                }
                Receive(socket, endPoint);
            }, null);
        }
开发者ID:kalantyr,项目名称:Parallel,代码行数:20,代码来源:Connector.cs

示例3: EndReceive

        FramingData EndReceive(Socket listenSocket, IAsyncResult result)
        {
            // if we've started the shutdown process, then we've disposed
            // the socket and calls to socket.EndReceive will throw
            if (closed)
                return null;

            byte[] buffer = ((SocketReceiveState)result.AsyncState).Buffer;
            Debug.Assert(buffer != null);
            FramingData data = null;

            try
            {
                int count = 0;

                lock (ThisLock)
                {
                    // if we've started the shutdown process, socket is disposed
                    // and calls to socket.EndReceive will throw
                    if (!closed)
                    {
                        EndPoint dummy = CreateDummyEndPoint(listenSocket);
                        count = listenSocket.EndReceiveFrom(result, ref dummy);
                    }
                }

                if (count > 0)
                {
                    data = FramingCodec.Decode(new ArraySegment<byte>(buffer, 0, count));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error in completing the async receive via EndReceiveFrom method.");
                Debug.WriteLine(e.ToString());
            }
            finally
            {
                if (data == null)
                {
                    this.bufferManager.ReturnBuffer(buffer);
                    buffer = null;
                }
            }

            return data;
        }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:47,代码来源:UdpSocketListener.cs

示例4: NetworkTargetUdpTest

        public void NetworkTargetUdpTest()
        {
            var target = new NetworkTarget()
            {
                Address = "udp://127.0.0.1:3002",
                Layout = "${message}\n",
                KeepConnection = true,
            };

            string expectedResult = string.Empty;

            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                Exception receiveException = null;
                var receivedMessages = new List<string>();
                var receiveFinished = new ManualResetEvent(false);

                byte[] receiveBuffer = new byte[4096];

                listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002));
                EndPoint remoteEndPoint = null;
                AsyncCallback receivedDatagram = null;

                receivedDatagram = result =>
                    {
                        try
                        {
                            int got = listener.EndReceiveFrom(result, ref remoteEndPoint);
                            string message = Encoding.UTF8.GetString(receiveBuffer, 0, got);
                            lock (receivedMessages)
                            {
                                receivedMessages.Add(message);
                                if (receivedMessages.Count == 100)
                                {
                                    receiveFinished.Set();
                                }
                            }

                            remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                            listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
                        }
                        catch (Exception ex)
                        {
                            receiveException = ex;
                        }
                    };

                remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);

                target.Initialize(new LoggingConfiguration());

                int pendingWrites = 100;
                var writeCompleted = new ManualResetEvent(false);
                var exceptions = new List<Exception>();

                AsyncContinuation writeFinished =
                    ex =>
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                            pendingWrites--;
                            if (pendingWrites == 0)
                            {
                                writeCompleted.Set();
                            }
                        }
                    };

                int toWrite = pendingWrites;
                for (int i = 0; i < toWrite; ++i)
                {
                    var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
                    target.WriteAsyncLogEvent(ev);
                    expectedResult += "message" + i + "\n";
                }

                Assert.IsTrue(writeCompleted.WaitOne(30000, false));
                target.Close();
                Assert.IsTrue(receiveFinished.WaitOne(30000, false));
                Assert.AreEqual(toWrite, receivedMessages.Count);
                for (int i = 0; i < toWrite; ++i)
                {
                    Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received.");
                }

                Assert.IsNull(receiveException, "Receive exception: " + receiveException);
            }
        }
开发者ID:rameshr,项目名称:NLog,代码行数:90,代码来源:NetworkTargetTests.cs

示例5: ReceiveCallback

        ////廣播3
        private void ReceiveCallback(IAsyncResult iar)
        {
            EndPoint remoteEnd = new IPEndPoint(IPAddress.Any, Int32.Parse(control.udp_port));
            sock = (Socket)iar.AsyncState;
            int received = sock.EndReceiveFrom(iar, ref remoteEnd);
            byte[] localMsg = new byte[received];
            Array.Copy(getdata, localMsg, received);
            var input = Encoding.UTF8.GetString(localMsg, 0, received);
            var inn = "UDP=" + input;

            _logger.Info(inn);

            input = input.Replace("\a", "");
            input = input.Replace("\r\n", string.Empty);
            analysis_type(input);

            sock.BeginReceiveFrom(getdata, 0, getdata.Length, SocketFlags.None, ref remoteEnd, new AsyncCallback(ReceiveCallback), sock);
        }
开发者ID:starboxs,项目名称:record,代码行数:19,代码来源:Form1.cs

示例6: _Receive

        private void _Receive(Socket Socket, byte[] Buffer)
        {
            while (true)
            {
                try
                {
                    const int offset = 0;
                    EndPoint endpoint = new IPEndPoint(Socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
                    Socket.BeginReceiveFrom(Buffer, offset, Buffer.Length, SocketFlags.None, ref endpoint, delegate(IAsyncResult ar)
                    {
                        try
                        {
                            int size = Socket.EndReceiveFrom(ar, ref endpoint);
                            if (this.Received != null)
                            {
                                this.Received((IPEndPoint)endpoint, new BufferData(Buffer).GetPartion(0, size));
                            }
                        }
                        catch (SocketException se)
                        {
                            if (!_CanIgnore(se))
                            {
                                throw se;
                            }
                        }

                        // Restart receive cycle
                        this._Receive(Socket, Buffer);
                    }, null);
                    return;
                }
                catch (SocketException se)
                {
                    if (!_CanIgnore(se))
                    {
                        throw se;
                    }
                }
            }
        }
开发者ID:dzamkov,项目名称:DUIP,代码行数:40,代码来源:UDP.cs


注:本文中的System.Net.Sockets.Socket.EndReceiveFrom方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。