Esempio n. 1
0
        public UdpPacket receive(UdpSocket fan, UdpPacket packet)
        {
            // create packet if null
            if (packet == null)
            {
                packet = UdpPacket.make(null, null, new MemBuf(1024));
            }

            // map buf bytes to packet
            MemBuf data = (MemBuf)packet.data();

            byte[]   buf    = data.m_buf;
            int      off    = data.m_pos;
            int      len    = buf.Length - off;
            int      recv   = 0;
            EndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            // receive
            if (isConnected(fan))
            {
                try
                {
                    recv   = m_dotnet.Receive(buf, off, len, SocketFlags.None);
                    sender = m_dotnet.RemoteEndPoint;
                }
                catch (SocketException e)
                {
                    // .NET will truncate contents correctly, but still throws a
                    // SocketException, so catch that specific case and allow it
                    if (e.Message.StartsWith("A message sent on a datagram socket was larger"))
                    {
                        recv   = len;
                        sender = m_dotnet.RemoteEndPoint;
                    }
                    else
                    {
                        throw IOErr.make(e).val;
                    }
                }
            }
            else
            {
                try
                {
                    if (m_dotnet == null)
                    {
                        m_dotnet = createSocket();
                    }
                    recv = m_dotnet.ReceiveFrom(buf, off, len, SocketFlags.None, ref sender);
                }
                catch (SocketException e)
                {
                    // .NET will truncate contents correctly, but still throws a
                    // SocketException, so catch that specific case and allow it
                    if (e.Message.StartsWith("A message sent on a datagram socket was larger"))
                    {
                        recv = len;
                    }
                    else
                    {
                        throw IOErr.make(e).val;
                    }
                }
            }

            // update packet with received message
            IPEndPoint endPoint = sender as IPEndPoint;

            packet.addr(IpAddrPeer.make(endPoint.Address));
            packet.port(Long.valueOf(endPoint.Port));
            data.m_pos  += recv;
            data.m_size += recv;

            return(packet);
        }