Exemplo n.º 1
0
    public byte[] Receive()
    {
        // Not sure this is the best way but
        // even when the socket is non-blocking,
        // it takes to much time to receive then
        // leave by a WouldBlock error.
        if (socket.Available == 0)
        {
            return(null);
        }

        var packet        = new byte[1500];
        var receiveResult = socket.Receive(packet);
        int packetSize    = receiveResult.Item1;
        var error         = receiveResult.Item2;

        if (error != SocketError.Success)
        {
            return(null);
        }

        if (packetSize != packet.Length)
        {
            var resizedPacket = new byte[packetSize];
            Array.Copy(packet, 0, resizedPacket, 0, packetSize);
            return(resizedPacket);
        }
        else
        {
            return(packet);
        }
    }
Exemplo n.º 2
0
    void OnReceive(IAsyncResult ar)
    {
        var s     = (UdpState)ar.AsyncState;
        var bytes = s.client.EndReceive(ar, ref s.dataStream);
        var msg   = Serializer.Deserialize <Message>(bytes);

        switch (msg.type)
        {
        case MessageType.None:
            break;

        case MessageType.LogIn:
            MessageReceived.Invoke(msg, s);
            break;

        case MessageType.LogOut:
            MessageReceived.Invoke(msg, s);
            break;

        case MessageType.Movement:
            MessageReceived.Invoke(msg, s);
            break;

        case MessageType.Tick:
            MessageReceived.Invoke(msg, s);
            break;
        }
        client.Receive(OnReceive);
    }
Exemplo n.º 3
0
        public void Start()
        {
            buffer = new SocketBuffer(1556);
            socket = factory.Udp();

            context.Queue.Add(() =>
            {
                socket.Bind();
                socket.Receive(buffer, OnReceived);
            });
        }
Exemplo n.º 4
0
        private void OnReceived(UdpSocketReceive received)
        {
            if (received.Status == SocketStatus.OK)
            {
                IPEndPoint endpoint = received.GetEndpoint();
                byte[]     data     = Bytes.Copy(buffer.Data, buffer.Offset, received.Count);

                socket.Receive(buffer, OnReceived);
                context.Queue.Add(OnReceived(endpoint, data));
            }
        }
    public static void Classify(UdpSocket udpSocket, ICollection <Receiver> receivers,
                                List <ConfirmPacketInfo> confirmPacketInfos,
                                Dictionary <int, SenderPacketInfo> senderPacketInfos)
    {
        foreach (var receiver in receivers)
        {
            senderPacketInfos.Add(receiver.SenderId, new SenderPacketInfo());
        }

        while (true)
        {
            var packet = udpSocket.Receive();
            if (packet == null)
            {
                break;
            }

            int senderId   = PacketUtils.getSessionIdFromSenderPacketBytes(packet.Bytes);
            var packetType = PacketUtils.getPacketTypeFromSenderPacketBytes(packet.Bytes);

            if (packetType == SenderPacketType.Confirm)
            {
                confirmPacketInfos.Add(new ConfirmPacketInfo(packet.EndPoint, ConfirmSenderPacket.Create(packet.Bytes)));
                continue;
            }

            // Ignore packet if it is sent from a sender without a corresponding receiver.
            if (!senderPacketInfos.TryGetValue(senderId, out SenderPacketInfo senderPacketInfo))
            {
                continue;
            }

            senderPacketInfo.ReceivedAny = true;
            switch (packetType)
            {
            case SenderPacketType.Heartbeat:
                break;

            case SenderPacketType.Video:
                senderPacketInfo.VideoPackets.Add(VideoSenderPacket.Create(packet.Bytes));
                break;

            case SenderPacketType.Parity:
                senderPacketInfo.ParityPackets.Add(ParitySenderPacket.Create(packet.Bytes));
                break;

            case SenderPacketType.Audio:
                senderPacketInfo.AudioPackets.Add(AudioSenderPacket.Create(packet.Bytes));
                break;
            }
        }
    }
Exemplo n.º 6
0
    public bool Receive(byte[] data, out int size, out INetworkAddress address)
    {
        var endPoint = new IPEndPoint(IPAddress.Any, 0);

        if (!m_socket.Receive(data, out size, ref endPoint))
        {
            address = null;
            return(false);
        }

        address = new UdpNetworkAddress(endPoint);

        return(true);
    }
Exemplo n.º 7
0
    public static SenderPacketCollection Receive(UdpSocket udpSocket, List <RemoteSender> remoteSenders)
    {
        var senderEndPoints        = new List <IPEndPoint>();
        var senderPacketCollection = new SenderPacketCollection();

        foreach (var remoteSender in remoteSenders)
        {
            senderEndPoints.Add(remoteSender.SenderEndPoint);
            senderPacketCollection.SenderPacketSets.Add(remoteSender.SenderSessionId, new SenderPacketSet());
        }

        // During this loop, SocketExceptions will have endpoint information.
        foreach (var senderEndPoint in senderEndPoints)
        {
            while (true)
            {
                var packet = udpSocket.ReceiveFrom(senderEndPoint);
                if (packet == null)
                {
                    break;
                }

                CollectPacket(packet, senderPacketCollection);
            }
        }

        // During this loop, SocketExceptions won't have endpoint information but connection messages will be received.
        while (true)
        {
            var packet = udpSocket.Receive();
            if (packet == null)
            {
                break;
            }

            CollectPacket(packet, senderPacketCollection);
        }

        return(senderPacketCollection);
    }
Exemplo n.º 8
0
        public void CanTransferDataUsingUdpSockets()
        {
            using (CompletionThread worker = new CompletionThread())
            {
                worker.Start();

                using (ManualResetEvent sync = new ManualResetEvent(false))
                {
                    IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 44556);
                    byte[]     data     = Encoding.ASCII.GetBytes("abc");

                    SocketBuffer  buffer  = new SocketBuffer(data);
                    SocketFactory factory = new SocketFactory(worker);

                    using (UdpSocket sender = factory.Udp())
                        using (UdpSocket receiver = factory.Udp())
                        {
                            sender.Bind();
                            receiver.Bind(endpoint.Port);

                            receiver.Receive(new SocketBuffer(10), received =>
                            {
                                Assert.That(received.Status, Is.EqualTo(SocketStatus.OK));
                                Assert.That(received.Count, Is.EqualTo(3));
                                Assert.That(received.Buffer.Data.Take(3), Is.EqualTo(data));

                                sync.Set();
                            });

                            sender.Send(endpoint, buffer, sent =>
                            {
                                Assert.That(sent.Status, Is.EqualTo(SocketStatus.OK));
                                Assert.That(sent.Count, Is.EqualTo(3));
                            });
                        }

                    Assert.That(sync.WaitOne(200), Is.True);
                }
            }
        }
    public static SenderPacketSet Receive(UdpSocket udpSocket)
    {
        var senderPacketSet = new SenderPacketSet();

        while (true)
        {
            var packet = udpSocket.Receive();
            if (packet == null)
            {
                break;
            }

            //int sessionId = PacketHelper.getSessionIdFromSenderPacketBytes(packet);
            senderPacketSet.ReceivedAny = true;
            switch (PacketHelper.getPacketTypeFromSenderPacketBytes(packet))
            {
            case SenderPacketType.Init:
                senderPacketSet.InitPacketDataList.Add(InitSenderPacketData.Parse(packet));
                break;

            case SenderPacketType.Frame:
                senderPacketSet.VideoPacketDataList.Add(VideoSenderPacketData.Parse(packet));
                break;

            case SenderPacketType.Parity:
                senderPacketSet.FecPacketDataList.Add(ParitySenderPacketData.Parse(packet));
                break;

            case SenderPacketType.Audio:
                senderPacketSet.AudioPacketDataList.Add(AudioSenderPacketData.Parse(packet));
                break;

            case SenderPacketType.Floor:
                senderPacketSet.FloorPacketDataList.Add(FloorSenderPacketData.Parse(packet));
                break;
            }
        }

        return(senderPacketSet);
    }
Exemplo n.º 10
0
        public void SendReceiveTest()
        {
            const string serverMessage = "HelloFromServer";
            const string clientMessage = "ResponseFromClient";

            IPEndPoint ep       = new IPEndPoint(IPAddress.Any, 666);
            IPEndPoint serverEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 666);
            UdpSocket  client   = new UdpSocket();
            UdpSocket  server   = new UdpSocket();

            server.Bind(666);
            Assert.AreEqual(SocketStatus.Done, client.Connect(serverEp));

            NetPacket packet       = new NetPacket();
            NetPacket clientPacket = new NetPacket();

            packet.WriteString(serverMessage);

            // Send message to client.
            Assert.AreEqual(SocketStatus.Done, server.Send(packet, client.LocalEndpoint));

            // Read message from server.
            Assert.AreEqual(SocketStatus.Done, client.Receive(clientPacket, ref ep));
            Assert.AreEqual(serverMessage, clientPacket.ReadString());

            // Send message back to server.
            clientPacket.Clear(SerializationMode.Writing);
            clientPacket.WriteString(clientMessage);
            Assert.AreEqual(SocketStatus.Done, client.Send(clientPacket));

            // Read message from client.
            Assert.AreEqual(SocketStatus.Done, server.Receive(packet, ref ep));
            Assert.AreEqual(clientMessage, packet.ReadString());

            client.Dispose();
            server.Dispose();
            packet.Dispose();
            clientPacket.Dispose();
        }
Exemplo n.º 11
0
    private void Update()
    {
        var         audioPacketDataSet = new List <AudioSenderPacketData>();
        SocketError error = SocketError.WouldBlock;

        while (true)
        {
            var packet = udpSocket.Receive(out error);
            if (packet == null)
            {
                break;
            }

            audioPacketDataSet.Add(AudioSenderPacketData.Parse(packet));
        }

        audioPacketDataSet.Sort((x, y) => x.frameId.CompareTo(y.frameId));

        float[] pcm   = new float[KH_SAMPLES_PER_FRAME * KH_CHANNEL_COUNT];
        int     index = 0;

        while (ringBuffer.FreeSamples >= pcm.Length)
        {
            if (index >= audioPacketDataSet.Count)
            {
                break;
            }

            var audioPacketData = audioPacketDataSet[index++];
            if (audioPacketData.frameId <= lastAudioFrameId)
            {
                continue;
            }

            audioDecoder.Decode(audioPacketData.opusFrame, pcm, KH_SAMPLES_PER_FRAME);
            ringBuffer.Write(pcm);
            lastAudioFrameId = audioPacketData.frameId;
        }
    }
Exemplo n.º 12
0
        private static void UDPListenerThread(IPv6Address ipAddress, ushort port)
        {
            UdpSocket receiver = new UdpSocket();

            receiver.Bind(ipAddress, port);
            IPv6EndPoint remoteIp = null;

            isUdpListenerRunning = true;

            while (isUdpListenerRunning)
            {
                if (receiver.Poll(-1, SelectMode.SelectRead))
                {
                    byte[] data    = receiver.Receive(ref remoteIp);
                    string message = Encoding.ASCII.GetString(data);
                    Console.WriteLine("\n");
                    Console.WriteLine("{0} bytes from {1} {2} {3}", message.Length, remoteIp.Address, remoteIp.Port, message);
                    Console.WriteLine(">");
                }
            }

            receiver.Close();
            receiver = null;
        }
    public void Ping(UdpSocket udpSocket)
    {
        int senderSessionId = -1;
        int pingCount       = 0;

        while (true)
        {
            bool initialized = false;
            udpSocket.Send(PacketHelper.createPingReceiverPacketBytes());
            ++pingCount;
            UnityEngine.Debug.Log("Sent ping");

            //Thread.Sleep(100);
            Thread.Sleep(300);

            SocketError error = SocketError.WouldBlock;
            while (true)
            {
                var packet = udpSocket.Receive(out error);
                if (packet == null)
                {
                    break;
                }

                int cursor    = 0;
                int sessionId = BitConverter.ToInt32(packet, cursor);
                cursor += 4;

                var packetType = (SenderPacketType)packet[cursor];
                cursor += 1;
                if (packetType != SenderPacketType.Init)
                {
                    UnityEngine.Debug.Log($"A different kind of a packet received before an init packet: {packetType}");
                    continue;
                }

                senderSessionId = sessionId;

                var initSenderPacketData = InitSenderPacketData.Parse(packet);

                textureGroup.SetWidth(initSenderPacketData.depthWidth);
                textureGroup.SetHeight(initSenderPacketData.depthHeight);
                PluginHelper.InitTextureGroup();

                colorDecoder = new Vp8Decoder();
                depthDecoder = new TrvlDecoder(initSenderPacketData.depthWidth * initSenderPacketData.depthHeight);

                azureKinectScreen.Setup(initSenderPacketData);

                initialized = true;
                break;
            }
            if (initialized)
            {
                break;
            }

            if (pingCount == 10)
            {
                UnityEngine.Debug.Log("Tried pinging 10 times and failed to received an init packet...\n");
                return;
            }
        }

        this.udpSocket = udpSocket;
        var videoPacketDataQueue = new ConcurrentQueue <VideoSenderPacketData>();
        var fecPacketDataQueue   = new ConcurrentQueue <FecSenderPacketData>();
        var audioPacketDataQueue = new ConcurrentQueue <AudioSenderPacketData>();

        var taskThread = new Thread(() =>
        {
            var receiveSenderPacketTask    = new ReceiveSenderPacketTask();
            var reassembleVideoMessageTask = new ReassembleVideoMessageTask();
            var consumeAudioPacketTask     = new ConsumeAudioPacketTask();

            while (!receiverStopped)
            {
                receiveSenderPacketTask.Run(this,
                                            senderSessionId,
                                            videoPacketDataQueue,
                                            fecPacketDataQueue,
                                            audioPacketDataQueue);
                reassembleVideoMessageTask.Run(this, videoPacketDataQueue, fecPacketDataQueue);
                consumeAudioPacketTask.Run(this, audioPacketDataQueue);
            }

            receiverStopped = true;
        });

        taskThread.Start();
    }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                string[] ports = SerialPort.GetPortNames();
                Console.WriteLine("COM port parameter not provided.");
                Console.WriteLine("Available serial ports: ");
                foreach (var serialPort in ports)
                {
                    Console.WriteLine(serialPort);
                }
                Console.ReadKey();
                return;
            }

            StreamUART uartStream = new StreamUART(args[0]);

            ncpInterface = new NcpInterface();

            try
            {
                ncpInterface.Open(uartStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                return;
            }

            // NetworkingInterface.SetupInterface(ncpInterface);

            Console.Write("Networkname:");
            string networkname = Console.ReadLine();

            Console.Write("Channel:");
            byte channel = Convert.ToByte(Console.ReadLine());

            Console.Write("Masterkey:");
            string masterkey = Console.ReadLine();

            Console.Write("Panid:");
            ushort panid = Convert.ToUInt16(Console.ReadLine());

            Console.Write("Listener port:");
            ushort port = Convert.ToUInt16(Console.ReadLine());

            try
            {
                ncpInterface.Form(networkname, channel, masterkey, panid);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
                return;
            }

            UdpSocket receiver = new UdpSocket();

            receiver.Bind(IPv6Address.IPv6Any, port);
            IPv6EndPoint remoteIp = null;

            while (true)
            {
                if (receiver.Poll(-1, SelectMode.SelectRead))
                {
                    byte[] data    = receiver.Receive(ref remoteIp);
                    string message = Encoding.ASCII.GetString(data);
                    Console.WriteLine("\n");
                    Console.WriteLine("{0} bytes from {1} {2} {3}", message.Length, remoteIp.Address, remoteIp.Port, message);
                    Console.WriteLine(">");
                }
            }
        }
        /// <summary>
        /// This thread function measures server latency every
        /// MEASUREMENT_INTERVAL milliseconds.
        ///
        /// Note that, because this function does not execute from a script
        /// context, it cannot call script functions.  Instead, a companion
        /// DelayCommand continuation on the main server thread will check the
        /// current latency value and save it as appropriate.
        /// </summary>
        private static void LatencyMeasurementThreadRoutine()
        {
            byte[]     PingMessage = { (byte)'B', (byte)'N', (byte)'L', (byte)'M', 0, 0, 0, 0, 0, 0, 0 };
            byte[]     Response;
            IPEndPoint SourceEndpoint = new IPEndPoint(0, 0);

            for (; ;)
            {
                //
                // Flush the socket receive queue.
                //

                UdpSocket.Client.ReceiveTimeout = 1;

                try
                {
                    for (;;)
                    {
                        UdpSocket.Receive(ref SourceEndpoint);
                    }
                }
                catch
                {
                }

                //
                // Now send a ping message and wait for a response or timeout.
                //

                UdpSocket.Client.ReceiveTimeout = MAX_PING;

                try
                {
                    uint Tick = (uint)Environment.TickCount;

                    UdpSocket.Send(PingMessage, PingMessage.Length);
                    Response = UdpSocket.Receive(ref SourceEndpoint);

                    Tick = (uint)Environment.TickCount - Tick;

                    if (Response.Length < 4 || Response[0] != (byte)'B' || Response[1] != (byte)'N' || Response[2] != (byte)'L' || Response[3] != (byte)'R')
                    {
                        throw new ApplicationException("Invalid BNLM response message received.");
                    }

                    //
                    // Report the response time.
                    //

                    lock (CurrentLatencyLock)
                    {
                        CurrentLatency = (int)Tick;
                    }
                }
                catch
                {
                    //
                    // Report a response time of -1 to indicate that no
                    // measurement could be taken.
                    //

                    lock (CurrentLatencyLock)
                    {
                        CurrentLatency = (int)-1;
                    }
                }

                Thread.Sleep(MEASUREMENT_INTERVAL);
            }
        }