Пример #1
0
        static void Main(string[] args)
        {
            int n = 200000;

            for (int i = 0; i < cycles; i++)
            {
                BytePacket p     = new BytePacket(40000);
                BytePacket p2    = new BytePacket(40000);
                Boh        value = Boh.Item1 | Boh.Item10 | Boh.Item11;
                watch.Reset();
                watch.Start();
                bool res  = false;
                bool res1 = false;
                bool res2 = false;
                for (int z = 0; z < n; z++)
                {
                }
                watch.Stop();



                long time = watch.ElapsedTicks;
                d1 += time;
                c1++;



                float f = 5f;
                float a;
                watch.Reset();
                watch.Start();
                for (int z = 0; z < n; z++)
                {
                }
                watch.Stop();



                long time2 = watch.ElapsedTicks;
                d2 += time2;
                c2++;

                if (time > time2)
                {
                    False++;
                }
                else
                {
                    True++;
                }

                AverageFirst  = d1 / c1;
                AverageSecond = d2 / c2;

                Console.WriteLine("Avrg first : {0} , win frames : {1} .   Avrg second : {2} , win frames : {3}", AverageFirst, True, AverageSecond, False);
            }

            Console.WriteLine("End");
            Console.ReadLine();
        }
Пример #2
0
 protected void Send(BytePacket <T> packet)
 {
     OutgoingMessages.Enqueue(new NetworkMessage <T> {
         Packet = packet
     });
     LatestSendTimestamp = DateTime.Now;
 }
    public override int FromPacketToAudioDataInt16(BytePacket packet, ref VoicePacketInfo info, byte[] out_audioData, int out_audioDataOffset)
    {
        //reads audio data length
        int count = packet.ReadInt();

        //Restarts packet buffer to use
        decompressBuffer.ResetSeekLength();

        //fills buffer with only audio data from given packet
        decompressBuffer.WriteByteData(packet.Data, packet.CurrentSeek, count);

        EVoiceResult res = EVoiceResult.k_EVoiceResultUnsupportedCodec;

        //number of bytes written
        uint b = 0;

        //audio data is decompressed
        res = SteamUser.DecompressVoice(decompressBuffer.Data, (uint)decompressBuffer.CurrentLength, out_audioData, (uint)out_audioData.Length, out b, info.Frequency);

        //if an error occurred packet is invalid
        if (res != EVoiceResult.k_EVoiceResultOK)
        {
            info.ValidPacketInfo = false;
        }

        return((int)b);
    }
Пример #4
0
 private void CallProc(BytePacket NP)
 {
     CallMutex.WaitOne();
     NameAndParams = NP;
     CallMutex.ReleaseMutex();
     ReturnEvent.WaitOne();
 }
Пример #5
0
        /// <summary>
        /// Initializes workflow , done automatically when SO is loaded. If fields are either not setted when this method is called or changed afterwards the workflow will remain in an incorrect state untill it is re-initialized
        /// </summary>
        public override void Initialize()
        {
            handlers = new Dictionary <ulong, VoiceHandler>();

            activeIdsToSendTo = new List <ulong>();

            if (mutedIds == null)
            {
                mutedIds = new Dictionary <ulong, MuteStatus>();

                LoadSavedMuteStatuses();
            }

            if (Manipulator)
            {
                int length = (Settings.MaxFrequency * Settings.MaxChannels) / 20;

                dataBuffer = (Manipulator.AvailableTypes & AudioDataTypeFlag.Single) != 0 ? new float[length] : null;

                dataBufferInt16 = (Manipulator.AvailableTypes & AudioDataTypeFlag.Int16) != 0 ? new byte[length * 2] : null;
            }
            else
            {
                dataBuffer      = null;
                dataBufferInt16 = null;
            }

            packetBuffer = Transport ? new BytePacket(Transport.MaxDataLength) : null;
        }
    public override int FromPacketToAudioData(BytePacket packet, ref VoicePacketInfo info, float[] out_audioData, int out_audioDataOffset)
    {
        int length    = packet.ReadInt();
        int frameSize = packet.ReadInt();

        return(decoder.Decode(packet.Data, packet.CurrentSeek, length, out_audioData, out_audioDataOffset, frameSize) * decoder.NumChannels);
    }
Пример #7
0
    void MSKVersionReport(uint Version)
    {
        BytePacket bp = new BytePacket();

        bp.Add("MSKVersionReport");
        bp.Add(Version);
        netThread.SendData(bp);
    }
Пример #8
0
 private void CallProc(byte [] NPData)
 {
     CallMutex.WaitOne();
     NameAndParams       = new BytePacket();
     NameAndParams.Bytes = NPData;
     CallMutex.ReleaseMutex();
     ReturnEvent.WaitOne();
 }
Пример #9
0
 protected void Send(BytePacket <T> packet, IPEndPoint target)
 {
     OutgoingMessages.Enqueue(new NetworkMessage <T> {
         Packet        = packet,
         TargetAddress = target,
     });
     LatestSendTimestamp = DateTime.Now;
 }
Пример #10
0
    public void TestProcessReceivedDataLengthRedLight()
    {
        BytePacket buffer = new BytePacket(20);

        byte[] receivedData = new byte[20];
        ulong  netId        = 5;

        transport.ProcessReceivedData(buffer, receivedData, 0, 20, netId);
        Assert.That(buffer.CurrentLength, Is.Not.EqualTo(20));
    }
Пример #11
0
 public override void SendToAll(BytePacket data, VoicePacketInfo info, List <ulong> receiversIds)
 {
     SentArray = new byte[data.Data.Length];
     ByteManipulator.Write <byte>(data.Data, 0, SentArray, 0, SentArray.Length);
     DataSent = data.CurrentLength;
     for (int i = 0; i < receiversIds.Count; i++)
     {
         DataSentTo.Add(receiversIds[i]);
     }
 }
Пример #12
0
        void OnDisable()
        {
            SaveCurrentMuteStatuses();

            activeIdsToSendTo = null;
            mutedIds          = null;
            handlers          = null;
            dataBuffer        = null;
            dataBufferInt16   = null;
            packetBuffer      = null;
        }
Пример #13
0
 public void SendData(BytePacket Data)
 {
     SendMutex.WaitOne();
     byte [] b2 = ToSendData;
     ToSendData = new byte[b2.GetLength(0) + 4 + Data.Bytes.GetLength(0)];
     System.Array.Copy(b2, ToSendData, b2.GetLength(0));
     System.Array.Copy(System.BitConverter.GetBytes(Data.Bytes.GetLength(0)), 0, ToSendData, b2.GetLength(0), 3);
     ToSendData[b2.GetLength(0) + 3] = 1;
     System.Array.Copy(Data.Bytes, 0, ToSendData, b2.GetLength(0) + 4, Data.Bytes.GetLength(0));
     SendMutex.ReleaseMutex();
 }
Пример #14
0
    public void TestSendToAllOthersCorrectPayloadLengthRedLight()
    {
        BytePacket p = new BytePacket(10);

        p.CurrentSeek   = 0;
        p.CurrentLength = 10;
        transport.SendToAll(p, new VoicePacketInfo(), new List <ulong>()
        {
            1
        });
        Assert.That(workflow.receivedData.Length, Is.Not.EqualTo(10));
    }
Пример #15
0
    public override int FromPacketToAudioDataInt16(BytePacket packet, ref VoicePacketInfo info, byte[] out_audioData, int out_audioDataOffset)
    {
        int dataCount = Mathf.Min(packet.CurrentLength - packet.CurrentSeek, out_audioData.Length - out_audioDataOffset);

        packet.ReadByteData(out_audioData, out_audioDataOffset, dataCount);
        FromPacketToAudioInt16 = true;
        if (UseInfo)
        {
            info = this.Info;
        }
        return(dataCount);
    }
Пример #16
0
    public void TestProcessReceivedDataFormatRedLight()
    {
        BytePacket buffer = new BytePacket(20);

        byte[] receivedData = new byte[20];
        ByteManipulator.Write(receivedData, 0, (ushort)4588);
        ByteManipulator.Write(receivedData, 2, (byte)5);
        ByteManipulator.Write(receivedData, 3, (byte)199);
        ulong           netId = 6;
        VoicePacketInfo info  = transport.ProcessReceivedData(buffer, receivedData, 0, 20, netId);

        Assert.That((byte)info.Format, Is.Not.EqualTo(99));
    }
Пример #17
0
    public void TestProcessReceivedDataChann()
    {
        BytePacket buffer = new BytePacket(20);

        byte[] receivedData = new byte[20];
        ByteManipulator.Write(receivedData, 0, (ushort)4588);
        ByteManipulator.Write(receivedData, 2, (byte)5);
        ByteManipulator.Write(receivedData, 3, (byte)99);
        ulong           netId = 5;
        VoicePacketInfo info  = transport.ProcessReceivedData(buffer, receivedData, 0, 20, netId);

        Assert.That(info.Channels, Is.EqualTo(5));
    }
Пример #18
0
    public void TestProcessReceivedDataValidPacketRedLight()
    {
        BytePacket buffer = new BytePacket(20);

        byte[] receivedData = new byte[20];
        ByteManipulator.Write(receivedData, 0, (ushort)4588);
        ByteManipulator.Write(receivedData, 2, (byte)5);
        ByteManipulator.Write(receivedData, 3, (byte)99);
        ulong           netId = 6;
        VoicePacketInfo info  = transport.ProcessReceivedData(buffer, receivedData, 0, 20, netId);

        Assert.That(info.ValidPacketInfo, Is.Not.False);
    }
Пример #19
0
        /// <summary>
        /// Upgrades the connection to the particular protocol. Handles the handshake.
        /// </summary>
        /// <param name="context"><see cref="ProcessingContext"/> for the current connection.</param>
        /// <param name="httpContext"><see cref="HttpContext"/> for the current connection.</param>
        /// <returns>The handlers that have been inserted in the pipeline.</returns>
        public WebSocketPipeline Upgrade(ProcessingContext context, HttpContext httpContext)
        {
            var request = httpContext.Request;
            var builder = new StringBuilder();

            builder.Append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
            builder.Append("Upgrade: WebSocket\r\n");
            builder.Append("Connection: Upgrade\r\n");
            builder.AppendFormat("Sec-WebSocket-Origin: {0}\r\n", request.Headers["Origin"]);
            //builder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", secure ? "wss" : "ws", request.Headers["Host"], request.Path);
            builder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", "ws", request.Headers["Host"], request.Path);

            if (request.Headers["Sec-WebSocket-Protocol"] != null)
            {
                builder.AppendFormat("Sec-WebSocket-Protocol: {0}\r\n", request.Headers["Sec-WebSocket-Protocol"]);
            }

            builder.Append("\r\n");

            var key1 = request.Headers["Sec-WebSocket-Key1"];
            var key2 = request.Headers["Sec-WebSocket-Key2"];

            // Get last bytes
            byte[] challenge = request.Body;

            // Compile the body
            var part1  = Encoding.ASCII.GetBytes(builder.ToString());
            var part2  = CalculateAnswerBytes(key1, key2, challenge);
            var buffer = new byte[part1.Length + part2.Length];

            Memory.Copy(part1, 0, buffer, 0, part1.Length);
            Memory.Copy(part2, 0, buffer, part1.Length, part2.Length);

            // Prepare the response packet
            var response = BytePacket.Acquire(buffer);

            // Get the channel
            var channel = httpContext.Connection;

            // Send the handshake response
            channel.Send(response);

            // Set the encoder & the decoder for this websocket handler
            channel.Encoding.PipelineAddLast(Encode.WebSocketDraft76);
            channel.Decoding.PipelineAddFirst(Decode.WebSocketDraft76);

            // Trace a websocket event
            NetTrace.WriteLine("Upgraded to Draft76 ", channel, NetTraceCategory.WebSocket);
            return(new WebSocketPipeline(Encode.WebSocketDraft76, Decode.WebSocketDraft76));
        }
Пример #20
0
    void Update()
    {
        int        n      = 200000;
        BytePacket first  = new BytePacket(n);
        BytePacket second = new BytePacket(n);


        watch.Reset();
        watch.Start();
        for (int z = 0; z < cycles; z++)
        {
        }
        watch.Stop();



        long time = watch.ElapsedMilliseconds;

        d1 += time;
        c1++;



        watch.Reset();
        watch.Start();
        for (int z = 0; z < cycles; z++)
        {
        }
        watch.Stop();



        long time2 = watch.ElapsedMilliseconds;

        d2 += time2;
        c2++;

        if (time > time2)
        {
            False++;
            //UnityEngine.Debug.LogFormat("First mode elapsed time = {0} , second mode elapsed time = {1} . Is first faster than second ? {2}", time, time2, time <= time2);
        }
        else
        {
            True++;
        }

        AverageFirst  = d1 / c1;
        AverageSecond = d2 / c2;
    }
Пример #21
0
    public void TestProcessReceivedDataPayloadIntegrity2RedLight()
    {
        BytePacket buffer = new BytePacket(20);

        byte[] receivedData = new byte[20];
        ByteManipulator.Write(receivedData, 0, (ushort)4588);
        ByteManipulator.Write(receivedData, 2, (byte)5);
        ByteManipulator.Write(receivedData, 3, (byte)99);
        ByteManipulator.Write(receivedData, 15, (int)77889);
        ulong netId = 5;

        transport.ProcessReceivedData(buffer, receivedData, 0, 20, netId);
        Assert.That(buffer.ReadInt(11), Is.Not.EqualTo(0));
    }
Пример #22
0
        /// <summary>
        /// Processes a Gamepacket into audio data in format Int16
        /// </summary>
        /// <param name="packet">GamePacket to process</param>
        /// <param name="info">data info</param>
        /// <param name="out_audioData">output array on which data will be written</param>
        /// <param name="out_audioDataOffset">output array start index</param>
        /// <returns>total number of bytes written</returns>
        public override int FromPacketToAudioDataInt16(BytePacket packet, ref VoicePacketInfo info, byte[] out_audioData, int out_audioDataOffset)
        {
            int maxP      = packet.CurrentLength - packet.CurrentSeek - sizeof(int);
            int dataCount = Mathf.Min(Mathf.Min(packet.ReadInt(), out_audioData.Length - out_audioDataOffset), maxP);

            if (dataCount <= 0)
            {
                info.ValidPacketInfo = false;
                return(dataCount);
            }

            packet.ReadByteData(out_audioData, out_audioDataOffset, dataCount);

            return(dataCount);
        }
Пример #23
0
        /// <summary>
        /// Sends a packet to a list of clients
        /// </summary>
        /// <param name="data">GamePacket that stores the data to send</param>
        /// <param name="info">data info</param>
        /// <param name="receiversIds">list of receivers ids that will receive the audio packet</param>
        public override void SendToAll(BytePacket data, VoicePacketInfo info, List <ulong> receiversIds)
        {
            toSend.CurrentSeek   = 0;
            toSend.CurrentLength = 0;

            toSend.Write(info.Frequency);
            toSend.Write(info.Channels);
            toSend.Write((byte)info.Format);

            int count = Mathf.Min(data.CurrentLength - data.CurrentSeek, toSend.Data.Length - toSend.CurrentSeek);

            toSend.WriteByteData(data.Data, data.CurrentSeek, count);

            SendToAllAction?.Invoke(toSend.Data, 0, toSend.CurrentLength, receiversIds);
        }
Пример #24
0
    public override int FromPacketToAudioData(BytePacket packet, ref VoicePacketInfo info, float[] out_audioData, int out_audioDataOffset)
    {
        int dataCount = Mathf.Min(packet.CurrentLength - packet.CurrentSeek, out_audioData.Length - out_audioDataOffset);

        for (int i = 0; i < dataCount / sizeof(float); i++)
        {
            out_audioData[i + out_audioDataOffset] = packet.ReadFloat();
        }
        FromPacketToAudio = true;
        if (UseInfo)
        {
            info = this.Info;
        }
        return(dataCount);
    }
Пример #25
0
        private void onCommandReceived(IClient client, BytePacket packet)
        {
            var cmd = (SyncerCommands)packet.Data;

            if (cmd == SyncerCommands.RequestMaster)
            {
                var master = sys.CheckoutRevision;
                var p      = new RevisionPacket(master);

                revisionTransporter.GetTransporterForClient(client).Send(p);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Пример #26
0
    public void TestSendToAllOthersCorrectPayloadDataRedLight()
    {
        BytePacket p = new BytePacket(10);

        p.Write(750);
        p.Write((ushort)110);
        p.Write((sbyte)-5);
        p.Write(false);
        p.Write((short)short.MinValue);
        p.CurrentSeek = 0;
        transport.SendToAll(p, new VoicePacketInfo(), new List <ulong>()
        {
            1
        });
        Assert.That(ByteManipulator.ReadInt32(workflow.receivedData, 4), Is.Not.EqualTo(0));
    }
Пример #27
0
    public void TestSendToAllOthersCorrectPayloadData4()
    {
        BytePacket p = new BytePacket(10);

        p.Write(750);
        p.Write((ushort)110);
        p.Write((sbyte)-5);
        p.Write(false);
        p.Write((short)-32767);
        p.CurrentSeek = 0;
        transport.SendToAll(p, new VoicePacketInfo(), new List <ulong>()
        {
            1
        });
        Assert.That(ByteManipulator.ReadInt16(workflow.receivedData, 12), Is.EqualTo(-32767));
    }
Пример #28
0
    public void TestFromAudioInt16ToPacketHeaderValue3()
    {
        byte[]     audiodata = new byte[800];
        BytePacket output    = new BytePacket(404);

        output.CurrentSeek   = 0;
        output.CurrentLength = 0;
        VoicePacketInfo info = new VoicePacketInfo();

        info.ValidPacketInfo = true;
        info.Frequency       = 48000;
        info.Channels        = 1;
        info.Format          = AudioDataTypeFlag.Both;
        manipulator.FromAudioDataToPacketInt16(audiodata, 0, audiodata.Length, ref info, output);
        Assert.That(output.ReadInt(0), Is.EqualTo(400));
    }
Пример #29
0
    public void TestFromAudioInt16ToPacketInvalid4()
    {
        byte[]     audiodata = new byte[200];
        BytePacket output    = new BytePacket(404);

        output.CurrentSeek   = 500;
        output.CurrentLength = 0;
        VoicePacketInfo info = new VoicePacketInfo();

        info.ValidPacketInfo = true;
        info.Frequency       = 48000;
        info.Channels        = 1;
        info.Format          = AudioDataTypeFlag.Both;
        manipulator.FromAudioDataToPacketInt16(audiodata, 0, audiodata.Length, ref info, output);
        Assert.That(info.ValidPacketInfo, Is.False);
    }
Пример #30
0
    public void TestFromAudioSingleToPacketValid()
    {
        float[]    audiodata = new float[200];
        BytePacket output    = new BytePacket(404);

        output.CurrentSeek   = 0;
        output.CurrentLength = 0;
        VoicePacketInfo info = new VoicePacketInfo();

        info.ValidPacketInfo = true;
        info.Frequency       = 48000;
        info.Channels        = 1;
        info.Format          = AudioDataTypeFlag.Both;
        manipulator.FromAudioDataToPacket(audiodata, 0, audiodata.Length, ref info, output);
        Assert.That(info.ValidPacketInfo, Is.True);
    }
        internal static void ReadCallback(IAsyncResult ar)
        {
            BaseClientStateObject sStateObject = (BaseClientStateObject)ar.AsyncState;

            int nRead = 0;

            try
            {
                nRead = sStateObject.ClientSocket.EndSend(ar);
                if (nRead == 0)
                {
                    sStateObject.Disconnect();
                    return;
                }
                switch (sStateObject.rMode)
                {
                    case ReadMode.Header:
                        sStateObject.headerIndex += nRead;

                        if (sStateObject.headerIndex != sStateObject.headerBuffer.Length)
                        {
                            sStateObject.ClientSocket.BeginReceive(
                                    sStateObject.headerBuffer,
                                    sStateObject.headerIndex,
                                    sStateObject.headerBuffer.Length - sStateObject.headerIndex,
                                    SocketFlags.None,
                                    new AsyncCallback(ReadCallback), sStateObject
                                );

                            return;
                        }

                        sStateObject.pHeader = MarshalExtensions.ByteArrayToStructure<PacketHeader>(sStateObject.headerBuffer);
                        sStateObject.headerBuffer = new byte[Marshal.SizeOf(typeof(PacketHeader))];
                        sStateObject.headerIndex = 0;

                        if (sStateObject.pHeader.DataLength > 0)
                        {
                            if (sStateObject.pHeader.DataLength > MaxAllowedDataSize)
                            {
                                sStateObject.Disconnect();
                                return;
                            }
                            sStateObject.rMode = ReadMode.Data;
                            sStateObject.dataIndex = 0;
                            sStateObject.dataBuffer = new byte[sStateObject.pHeader.DataLength];
                            sStateObject.ClientSocket.BeginReceive(
                                    sStateObject.dataBuffer,
                                    sStateObject.dataIndex,
                                    sStateObject.dataBuffer.Length - sStateObject.dataIndex,
                                    SocketFlags.None,
                                    new AsyncCallback(ReadCallback), sStateObject
                                );
                            return;
                        }

                        break;

                    case ReadMode.Data:
                        sStateObject.dataIndex += nRead;

                        if (sStateObject.dataIndex != sStateObject.dataBuffer.Length)
                        {
                            sStateObject.ClientSocket.BeginReceive(
                                    sStateObject.dataBuffer,
                                    sStateObject.dataIndex,
                                    sStateObject.dataBuffer.Length - sStateObject.dataIndex,
                                    SocketFlags.None,
                                    new AsyncCallback(ReadCallback), sStateObject
                                );

                            return;
                        }

                        BytePacket bPacket = new BytePacket();
                        bPacket.FromExisting(sStateObject.pHeader, sStateObject.dataBuffer);

                        if (sStateObject.OnPacketReceived[bPacket.Header.PacketType] != null)
                        {
                            Thread tOnPacketReceived = new Thread(
                                () => {
                                    try
                                    {
                                        sStateObject.OnPacketReceived[bPacket.Header.PacketType](sStateObject, bPacket);
                                    }
                                    catch { sStateObject.Disconnect(); }
                                });

                            tOnPacketReceived.Start();
                        }

                        sStateObject.rMode = ReadMode.Header;
                        sStateObject.ClientSocket.BeginReceive(
                            sStateObject.headerBuffer,
                            sStateObject.headerIndex,
                            sStateObject.headerBuffer.Length - sStateObject.headerIndex,
                            SocketFlags.None,
                            new AsyncCallback(ReadCallback), sStateObject
                        );

                        break;
                }
            }
            catch
            {
                sStateObject.Disconnect();
                return;
            }
        }