Example #1
0
        public PollingServer(IServerNetworkLinkLayer networkLinkLayer, IProtocolSpecification <TClientControlFrameType, TClientDataFrameType, TServerDataFrameType> specification)
        {
            if (networkLinkLayer == null)
            {
                throw new ArgumentNullException("networkLinkLayer", "Logical Link Layer is not set!");
            }

            if (specification == null)
            {
                throw new ArgumentNullException("specification", "Protocol-Specification cannot be null!");
            }

            if (specification.ClientEncoder == null)
            {
                throw new ArgumentException("specification", string.Format("ClientEncoder must be provided for given ProtocolSpecification '{0}'", specification.GetType().Name));
            }

            if (specification.ServerEncoder == null)
            {
                throw new ArgumentException("specification", string.Format("ServerEncoder must be provided for given ProtocolSpecification '{0}'", specification.GetType().Name));
            }

            this.protocolSpecification = specification;

            this.networkLinkLayer = networkLinkLayer;
            this.encoder          = specification.ClientEncoder;
            this.decoder          = specification.ServerEncoder;

            this.maxOutgoingSequenceValue = specification.MaxServerSequenceValue;
            this.maxIncomingSequenceValue = specification.MaxClientSequenceValue;

            this.networkLinkLayer.PollHandler = this.NetworkLayerPollHandler;
        }
Example #2
0
        void Write(OpCode opCode, byte[] payload = null)
        {
            var writeBufferSize = 4 + (payload == null ? 0 : payload.Length);

            using (var ms = new MemoryStream(writeBufferSize))
            {
                int bytesWritten = FrameEncoder.Write(ms, opCode, false, payload);

                try
                {
                    lock (stateLock)
                    {
#if NETSTANDARD
                        if (ms.TryGetBuffer(out var buffer))
                        {
                            Write(buffer.Array, 0, bytesWritten);
                            onBytesSent(bytesWritten);
                        }
#endif
#if NET452
                        Write(ms.GetBuffer(), 0, bytesWritten);
                        onBytesSent(bytesWritten);
#endif
                    }
                }
                catch (SessionStreamException e)
                {
                    throw new WebSocketException("Exception writing to websocket stream", e);
                }
            }
        }
Example #3
0
        public void FrameEncoding()
        {
            JoinRequestMessage originalMessage = new JoinRequestMessage();

            originalMessage.BubbleId              = Guid.NewGuid();
            originalMessage.BubbleName            = "TestBubbleName";
            originalMessage.LocationName          = "TestLocation";
            originalMessage.IdentityProviderUrl   = "IdentityProviderUrl";
            originalMessage.ParticipantIdentifier = "TestParticipantName";
            originalMessage.ParticipantSecret     = "TestParticipantPassphrase";
            originalMessage.ParticipantRealTime   = 10;

            originalMessage.ProgramName          = "TestProgramName";
            originalMessage.ProgramMajorVersion  = 1;
            originalMessage.ProgramMinorVersion  = 2;
            originalMessage.ProtocolMajorVersion = 3;
            originalMessage.ProtocolMinorVersion = 4;

            Session senderSession = new Session();

            senderSession.Send(originalMessage);

            byte[] packetBytes = new byte[300];
            bool   quaranteed  = false;

            FrameEncoder.EncodeFrame(senderSession, packetBytes, 0, ref quaranteed);

            Assert.IsTrue(quaranteed);

            Session receiverSession = new Session();

            FrameEncoder.DecodeFrame(receiverSession, packetBytes, 0, ref quaranteed);

            Assert.IsTrue(quaranteed);

            Message decodedMessage = receiverSession.Receive();

            Assert.IsNotNull(decodedMessage);

            Assert.AreEqual(0, senderSession.GetOutboundMessageCount());
            Assert.AreEqual(0, senderSession.GetPartiallySentMessageCount());
            Assert.AreEqual(0, senderSession.AvailableMessages);
            Assert.AreEqual(0, senderSession.GetPartiallyReceivedMessageCount());
            Assert.AreEqual(0, receiverSession.GetOutboundMessageCount());
            Assert.AreEqual(0, receiverSession.GetPartiallySentMessageCount());
            Assert.AreEqual(0, receiverSession.AvailableMessages);
            Assert.AreEqual(0, receiverSession.GetPartiallyReceivedMessageCount());



            decodedMessage.MessageId = originalMessage.MessageId;

            decodedMessage.IsAutoRelease = false;

            String originalMessageString = originalMessage.ToString();
            String decodedMessageString  = decodedMessage.ToString();

            Assert.AreEqual(originalMessageString, decodedMessageString);
        }
        static void Main(string[] args)

        {
            MMDevice dev = MMDeviceEnumerator.DefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);

            capture        = new WasapiLoopbackCapture();
            capture.Device = dev;
            capture.Initialize();

            SoundInSource soundInSource = new SoundInSource(capture);

            nStream = new SingleBlockNotificationStream(soundInSource.ToSampleSource());
            final   = nStream.ToWaveSource();
            nStream.SingleBlockRead     += NStream_SingleBlockRead;
            soundInSource.DataAvailable += encode;
            trashBuf = new byte[final.WaveFormat.BytesPerSecond / 2];

            Console.WriteLine($"sample rate:{capture.WaveFormat.SampleRate}");
            Console.WriteLine($"bits per sample:{capture.WaveFormat.BitsPerSample }");
            Console.WriteLine($"channels:{capture.WaveFormat.Channels }");
            Console.WriteLine($"bytes per sample:{capture.WaveFormat.BytesPerSample }");
            Console.WriteLine($"bytes per second:{capture.WaveFormat.BytesPerSecond }");
            Console.WriteLine($"AudioEncoding:{capture.WaveFormat.WaveFormatTag  }");


            EncodingContext context = FrameEncoder.GetDefaultsContext();

            context.Channels        = 6;
            context.SampleRate      = capture.WaveFormat.SampleRate;
            context.AudioCodingMode = AudioCodingMode.Front3Rear2;
            context.HasLfe          = true;
            context.SampleFormat    = A52SampleFormat.Float;
            enc = new FrameEncoderFloat(ref context);

            //_writer = new WaveWriter("test.ac3", final.WaveFormat);


            capture.Start();

            wBuffSrc = new WriteableBufferingSource(new WaveFormat(capture.WaveFormat.SampleRate, capture.WaveFormat.BitsPerSample, capture.WaveFormat.Channels, AudioEncoding.WAVE_FORMAT_DOLBY_AC3_SPDIF), (int)capture.WaveFormat.MillisecondsToBytes(20));

            w = new WasapiOut2(false, AudioClientShareMode.Shared, 20);

            w.Device = MMDeviceEnumerator.EnumerateDevices(DataFlow.Render, DeviceState.Active).Where(x => x.FriendlyName.Contains("Digital")).Single();
            AudioClient a = AudioClient.FromMMDevice(w.Device);

            w.Initialize(wBuffSrc);
            w.Play();


            Task.Run(async() => await encoderThread());
            //encodeSinus();

            Console.ReadLine();

            System.Environment.Exit(0);
        }
Example #5
0
        public void SendClose(ushort statusCode = 0, string reason = null)
        {
            lock (stateLock)
            {
                if (sentClose)
                {
                    return;
                }

                sentClose = true;
            }

            Write(OpCode.Close, FrameEncoder.GetClosePayload(statusCode, reason));
        }
Example #6
0
        public ClientTransportLayer(IClientNetworkLinkLayer networkLayer, IClientFrameEncoder <TSendControlFrameType, TSendDataFrameType> encoder, FrameEncoder <TReceiveDataType> decoder, int maxClientSequenceValue, int maxServerSequenceValue)
        {
            this.networkLayer = networkLayer;

            this.encoder = encoder;
            this.decoder = decoder;

            this.maxClientSequenceValue = maxClientSequenceValue;

            this.incomingBuffer = new FrameBuffer <TReceiveDataType>(maxServerSequenceValue);
            this.incomingBuffer.FrameBlockReceived += this.IncomingBufferOnFrameBlockReceived;

            this.localSequenceNr = new Random((int)DateTime.UtcNow.Ticks).Next(1, maxClientSequenceValue);

            this.networkLayer.DataReceived += this.NetworkLayerOnDataReceived;
        }
Example #7
0
        public async Task ActAsServerAsync(Socket clientSocket)
        {
            var channel = new SocketChannel();

            channel.Assign(clientSocket);

            _encodingContext = new EncodingContext(channel);
            _decodingContext = new DecodingContext(_channel);
            _encoder         = new FrameEncoder(_encodingContext);
            _decoder         = new FrameDecoder();
            await channel.ReceiveAsync(_decodingContext.Buffer, _decodingContext.Offset, _decodingContext.Capacity);

            if (_decodingContext.BytesLeftToProcess < ClientPreface.Length)
            {
                //TODO: Invalid protocol
            }

            // ReSharper disable once LoopCanBeConvertedToQuery
            for (var i = 0; i < ClientPreface.Length; i++)
            {
                if (ClientPreface[i] != _decodingContext.Buffer[_decodingContext.Offset + i])
                {
                    throw new Http2Exception(Http2ErrorCode.ProtocolError, "ClientPreface was not valid.");
                }
            }
            _decodingContext.Offset             += ClientPreface.Length;
            _decodingContext.BytesLeftToProcess -= ClientPreface.Length;

            // didn't get the settings frame directly
            if (_decodingContext.BytesLeftToProcess == 0)
            {
                await _decodingContext.ReceiveMoreAsync();
            }

            var frame = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame;

            if (frame == null)
            {
                throw new Http2Exception(Http2ErrorCode.ProtocolError, "Expected SETTINGS frame after client preface.");
            }

            //ack on client frame
            await _encoder.EncodeAsync(new SettingsFrame { IsAcknowledgment = true });

            // our own settings.
            await _encoder.EncodeAsync(new SettingsFrame());
        }
Example #8
0
        public async Task ConnectAsync(Uri uri)
        {
            if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                _channel = new SecureSocketChannel();
                await _channel.ConnectAsync(uri.Host, uri.Port == 0? 443 : uri.Port);
            }
            else
            {
                _channel = new SocketChannel();
                await _channel.ConnectAsync(uri.Host, uri.Port == 0? 443 : uri.Port);
            }

            _encodingContext = new EncodingContext(_channel);
            _encoder         = new FrameEncoder(_encodingContext);

            Buffer.BlockCopy(ClientPreface, 0, _encodingContext.Buffer, _encodingContext.Offset, ClientPreface.Length);
            _encodingContext.Offset += ClientPreface.Length;
            var settingsFrame = new SettingsFrame();
            await _encoder.EncodeAsync(settingsFrame);

            if (_encodingContext.ContainsData)
            {
                await _encodingContext.SendAsync();
            }

            var ackOnOurFrame = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame;

            if (ackOnOurFrame == null)
            {
                //TODO: Protocol error
            }

            var serverSettings = await _decoder.DecodeAsync(_decodingContext) as SettingsFrame;

            if (serverSettings == null)
            {
                //TODO: protocol error
            }
        }
Example #9
0
        public async Task ConnectAsync(Uri uri)
        {
            int port = uri.Port;

            if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                _socket = new SecureSocketChannel();
                if (port == 0)
                {
                    port = uri.Port == 0 ? 443 : uri.Port;
                }
            }
            else
            {
                _socket = new SocketChannel();
                if (port == 0)
                {
                    port = uri.Port == 0 ? 80 : uri.Port;
                }
            }


            await _socket.ConnectAsync(uri.Host, port);

            _context = new EncodingContext(_socket);
            _encoder = new FrameEncoder(_context);


            var http2Settings = new SettingsFrame();

            http2Settings.Encode(1, new EncodingContext());

            var handshake = string.Format(@"GET / HTTP/1.1
Host: {0}
Connection: Upgrade, HTTP2-Settings
Upgrade: h2c
HTTP2-Settings: {1}
     ", uri.Host, http2Settings);
        }
Example #10
0
 public PollingClient(IClientNetworkLinkLayer clientNetworkLinkLayer, IClientFrameEncoder <TClientControlFrameType, TClientDataFrameType> clientEncoder, FrameEncoder <TServerDataFrameType> serverEncoder, int maxClientSequenceValue,
                      int maxServerSequenceValue)
     : this(
         clientNetworkLinkLayer,
         new DefaultProtocolSpecification <TClientControlFrameType, TClientDataFrameType, TServerDataFrameType>()
 {
     ClientEncoder = clientEncoder,
     ServerEncoder = serverEncoder,
     MaxClientSequenceValue = maxClientSequenceValue,
     MaxServerSequenceValue = maxServerSequenceValue
 })
 {
 }
Example #11
0
 public PollingClient(IClientNetworkLinkLayer clientNetworkLinkLayer, IClientFrameEncoder <TClientControlFrameType, TClientDataFrameType> clientEncoder, FrameEncoder <TServerDataFrameType> serverEncoder)
     : this(clientNetworkLinkLayer, new DefaultProtocolSpecification <TClientControlFrameType, TClientDataFrameType, TServerDataFrameType>() { ClientEncoder = clientEncoder, ServerEncoder = serverEncoder })
 {
 }
Example #12
0
 public PollingServer(IServerNetworkLinkLayer networkLinkLayer, IClientFrameEncoder <TClientControlFrameType, TClientDataFrameType> encoder, FrameEncoder <TServerDataFrameType> decoder, int maxIncomingSequenceValue, int maxOutgoingSequenceValue)
     : this(networkLinkLayer, new DefaultProtocolSpecification <TClientControlFrameType, TClientDataFrameType, TServerDataFrameType>() { ClientEncoder = encoder, ServerEncoder = decoder, MaxClientSequenceValue = maxIncomingSequenceValue, MaxServerSequenceValue = maxOutgoingSequenceValue })
 {
 }
Example #13
0
 public void SendCommand(Transfer transfer, ByteBuffer payload) =>
 Send(buffer => FrameEncoder.Encode(buffer, Channel, transfer, payload));
Example #14
0
 public void SendCommand(ushort channel, DescribedList command, FrameType type = FrameType.Amqp) =>
 Send(buffer => FrameEncoder.Encode(buffer, type, channel, command));