private static async Task ReadNullPacket(Stream stream) { var reader = new ProtocolReader(stream); var packet = await Connection.ReadPacketAsJObject(reader); Assert.IsNull(packet); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.ObjectId = reader.ReadInt32(); this.CharId = reader.ReadInt32(); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.ErrorId = reader.ReadInt32(); this.ErrorDescription = reader.ReadString(); }
public MyClientProtocol(ConnectionContext connection) { _connection = connection; _reader = connection.CreateReader(); _messageWriter = new MyRequestMessageWriter(); }
public override async Task OnConnectedAsync(ConnectionContext connection) { ProtocolReader protocolReader = connection.CreateReader(); CustomProtocol customProtocol = new(); string message = "first\n"; Memory <byte> buffer = connection.Transport.Output.GetMemory(0x10)[..0x10];
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.ObjectId = reader.ReadInt32(); this.Text = reader.ReadString(); }
[InlineData("2F100718D9A3C41E00", "1018D6728000")] // Qbox van R. versie 47 nieuw public async Task Handle_NoMeterMessage(string message, string response) { string correlationId = Guid.NewGuid().ToString(); var mini = new Mini(); var ctx = new QboxDataDumpContext(message, 16, "localhost", "::1", mini); var parserFactoryMock = new Mock <IParserFactory>(); var protocolReader = new ProtocolReader(_protocolReaderLoggerMock.Object, message.AsMemory()); var protocolReaderFactoryMock = new Mock <IProtocolReaderFactory>(); protocolReaderFactoryMock.Setup(pr => pr.Create(It.IsAny <ReadOnlyMemory <char> >())).Returns(protocolReader); var smartMeterCounterParser = new SmartMeterCounterParser(_smartMeterLoggerMock.Object, _validators); parserFactoryMock.Setup(pf => pf.GetParser(It.IsAny <string>())).Returns(new MiniR21(_miniLoggerMock.Object, protocolReaderFactoryMock.Object, smartMeterCounterParser)); var sut = new QboxNextDataHandler(correlationId, ctx, parserFactoryMock.Object, _counterStoreServiceMock.Object, _stateStoreServiceMock.Object, _dateMock.Object, _qboxNextDataHandlerLoggerMock.Object); var result = await sut.HandleAsync(); var resultAsText = result.Trim('\x02', '\x03'); resultAsText.Should().Be(response); }
private static async Task TestNoPacketAsync(Packet packet) { var reader = new ProtocolReader(packet.AsStream()); var obj = await Connection.ReadPacketAsJObject(reader); Assert.IsNull(obj); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.Tiles = reader.ReadVector <TilePoint>(new ReadItemDelegate(reader.ReadTilePoint)); this.NewObjects = reader.ReadVector <GameObject>(new ReadItemDelegate(reader.ReadGameObject)); this.Drops = reader.ReadVector <int>(new ReadItemDelegate(() => (object)reader.ReadInt32())); // idk why the f**k I have to use lambda }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.TickId = reader.ReadInt32(); this.TickTime = reader.ReadInt32(); this.Statuses = reader.ReadVector<ObjectStatusData>(new ReadItemDelegate(reader.ReadObjectStatusData)); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.Tiles = reader.ReadVector<TilePoint>(new ReadItemDelegate(reader.ReadTilePoint)); this.NewObjects = reader.ReadVector<GameObject>(new ReadItemDelegate(reader.ReadGameObject)); this.Drops = reader.ReadVector<int>(new ReadItemDelegate(() => (object)reader.ReadInt32())); // idk why the f**k I have to use lambda }
public CobbleConnection(ConnectionContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); _reader = context.CreateReader(); _writer = context.CreateWriter(); _protocol = new HandshakingProtocol(); }
private static async Task TestValidPacketAsync(Packet packet) { Assert.IsFalse(packet.BadHeaders || packet.BadContent); var reader = new ProtocolReader(packet.AsStream()); var obj = await Connection.ReadPacketAsJObject(reader); Assert.IsNotNull(obj); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.TickId = reader.ReadInt32(); this.TickTime = reader.ReadInt32(); this.Statuses = reader.ReadVector <ObjectStatusData>(new ReadItemDelegate(reader.ReadObjectStatusData)); }
public override async Task OnConnectedAsync(ConnectionContext connection) { if (connection is null) { throw new ArgumentNullException(nameof(connection)); } using IDisposable loggerScope = _logger.BeginScope("Peer {PeerId} connected to server {ServerEndpoint}", connection.ConnectionId, connection.LocalEndPoint); ProtocolReader reader = connection.CreateReader(); INetworkProtocolMessageSerializer protocol = _serviceProvider.GetRequiredService <INetworkProtocolMessageSerializer>(); using IPeerContext peerContext = _peerContextFactory.CreateIncomingPeerContext(connection.ConnectionId, connection.LocalEndPoint !.AsIPEndPoint().EnsureIPv6(), connection.RemoteEndPoint !.AsIPEndPoint().EnsureIPv6(), new NetworkMessageWriter(protocol, connection.CreateWriter())); using CancellationTokenRegistration cancellationRegistration = peerContext.ConnectionCancellationTokenSource.Token.Register(() => { connection.Abort(new ConnectionAbortedException("Requested by PeerContext")); }); connection.Features.Set(peerContext); protocol.SetPeerContext(peerContext); if (EnsurePeerCanConnect(connection, peerContext)) { _eventBus.Publish(new PeerConnected(peerContext)); await _networkMessageProcessorFactory.StartProcessorsAsync(peerContext).ConfigureAwait(false); while (true) { try { ProtocolReadResult <INetworkMessage> result = await reader.ReadAsync(protocol).ConfigureAwait(false); if (result.IsCompleted) { break; } await ProcessMessageAsync(result.Message, peerContext, connection.ConnectionClosed).ConfigureAwait(false); } catch (Exception ex) { _logger.LogDebug(ex, "Unexpected connection terminated because of {DisconnectionReason}.", ex.Message); break; } finally { reader.Advance(); } } return; } }
public async Task ConnectAsync(EndPoint endPoint) { // REVIEW: Should this be a static factory? _connection = await _client.ConnectAsync(endPoint).ConfigureAwait(false); _writer = _connection.CreateWriter(); _reader = _connection.CreateReader(); _readingTask = ProcessReadsAsync(); }
public MultiplexingSocketProtocol(ConnectionContext connection, IMessageReader <TInbound> messageReader, IMessageWriter <TOutbound> messageWriter, IMessageIdGenerator messageIdGenerator, IMessageIdParser messageIdParser) { this.connection = connection ?? throw new ArgumentNullException(nameof(connection)); this.reader = new ProtocolReader(this.connection.Transport.Input); this.writer = new ProtocolWriter(this.connection.Transport.Output); this.wrappedReader = new WrappedMessageReader <TInbound>(messageIdParser, messageReader); this.wrappedWriter = new WrappedMessageWriter <TOutbound>(messageIdParser, messageWriter); this.sourcePool = new ObjectPool <PooledValueTaskSource <MessageId> >(() => { return(new PooledValueTaskSource <MessageId>()); }, 100); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.EffectType = reader.ReadByte(); this.TargetObjectId = reader.ReadInt32(); this.Position1 = reader.ReadTilePoint(); this.Position2 = reader.ReadTilePoint(); this.Colour = reader.ReadInt32(); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.TargetId = reader.ReadInt32(); this.ConditionEffect = reader.ReadByte(); this.DamageAmount = reader.ReadUInt16(); this.BulletId = reader.ReadByte(); this.ObjectId = reader.ReadInt32(); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.BulletId = reader.ReadByte(); this.OwnerId = reader.ReadInt32(); this.ContainerType = reader.ReadInt16(); this.StartingPosition = reader.ReadTilePoint(); this.Angle = reader.ReadSingle(); this.Damage = reader.ReadInt16(); }
public void Setup() { // Establish as much that can be pre-calculated as possible. dataPipe = new Pipe(); writer = dataPipe.Writer; delimitedMessageReader = new SimpleReader(MessageSize); data = new byte[MessageSize]; data.AsSpan().Fill(1); halfDataSize = MessageSize / 2; protReader = new ProtocolReader(dataPipe.Reader); }
public MemcachedProtocol(ConnectionContext connection) { _connection = connection; _protocolReader = connection.CreateReader(); _protocolWriter = connection.CreateWriter(); _semaphore = new SemaphoreSlim(1); _memcachedMessageWriter = new MemcachedMessageWriter(); _memcachedMessageReader = new MemcachedMessageReader(); }
private static async Task ReadInvalidPacket(Stream stream) { var reader = new ProtocolReader(stream); try { var packet = await Connection.ReadPacketAsJObject(reader); Assert.IsNotNull(packet); Assert.Fail("Failed to raise InvalidDataException."); } catch (InvalidDataException) { } }
public void Load_Operation_Gets_File_Content_Into_StringArray() { string testFileContent = "Line 1" + Environment.NewLine + "Line 2 Line 2" + Environment.NewLine + "Line 3 Line 3 Line 3"; File.WriteAllText(testProtocolFilePath, testFileContent); ProtocolReader protocolReader = new ProtocolReader(testProtocolFilePath); protocolReader.Load(); CollectionAssert.AreEqual(testFileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None), protocolReader.LinesFromFile); }
private static async Task TestInvalidPacketAsync(Packet packet) { Assert.IsTrue(packet.BadHeaders || packet.BadContent); var reader = new ProtocolReader(packet.AsStream()); try { var obj = await Connection.ReadPacketAsJObject(reader); Assert.IsNotNull(obj); Assert.Fail("Failed to raise InvalidDataException."); } catch (InvalidDataException) { } }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.Width = reader.ReadInt32(); this.Height = reader.ReadInt32(); this.Name = reader.ReadString(); this.FP = reader.ReadUInt32(); this.Background = reader.ReadInt32(); this.AllowPlayerTeleport = reader.ReadBool(); this.ShowDisplays = reader.ReadBool(); this.ExtraXml = reader.ReadVector<string>(new ReadItemDelegate(reader.ReadLongString)); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.Width = reader.ReadInt32(); this.Height = reader.ReadInt32(); this.Name = reader.ReadString(); this.FP = reader.ReadUInt32(); this.Background = reader.ReadInt32(); this.AllowPlayerTeleport = reader.ReadBool(); this.ShowDisplays = reader.ReadBool(); this.ExtraXml = reader.ReadVector <string>(new ReadItemDelegate(reader.ReadLongString)); }
public override void Read(byte[] packet) { ProtocolReader reader = new ProtocolReader(packet); this.Name = reader.ReadString(); this.ObjectId = reader.ReadInt32(); this.ObjectType = reader.ReadInt16(); this.Texture1Id = reader.ReadInt32(); this.Texture2Id = reader.ReadInt32(); this.NumStars = reader.ReadInt32(); this.Recipient = reader.ReadString(); this.Text = reader.ReadString(); this.CleanText = reader.ReadString(); }
/// <summary>COM_PING, check if the server is alive.</summary> public OkPacket Ping() { using (var stream = client.GetStream()) { var readWriteBuffer = InternalMemoryPool.GetBuffer(); var writer = PacketWriter.Create(readWriteBuffer); ProtocolWriter.WritePing(ref writer); var reader = SyncWriteAndRead(ref writer, 0, stream); var response = ProtocolReader.ReadResponsePacket(ref reader); response.ThrowIfError(); return((OkPacket)response); } }
public TextResultSet Query(string query) { var stream = client.GetStream(); var readWriteBuffer = InternalMemoryPool.GetBuffer(); var writer = PacketWriter.Create(readWriteBuffer); ProtocolWriter.WriteQuery(ref writer, query); var reader = SyncWriteAndRead(ref writer, 0, stream); // TODO: Ok or ResultSet? var set = ProtocolReader.ReadTextResultSet(ref reader); return(set); }
[InlineData("2F100718D9A3C41E00", MiniState.Operational)] // Qbox van R. public void Parse(string message, MiniState miniState) { // Arrange var protocolReader = new ProtocolReader(_protocolReaderLoggerMock.Object, message.AsMemory()); var protocolReaderFactoryMock = new Mock <IProtocolReaderFactory>(); protocolReaderFactoryMock.Setup(pr => pr.Create(It.IsAny <ReadOnlyMemory <char> >())).Returns(protocolReader); var smartMeterCounterParser = new SmartMeterCounterParser(_smartMeterLoggerMock.Object, _validators); var sut = new MiniR07(_miniLoggerMock.Object, protocolReaderFactoryMock.Object, smartMeterCounterParser); // Act var result = (MiniParseResult)sut.Parse(message); // Assert result.Model.Status.Status.Should().Be(miniState); }
public StatementPrepareOk Prepare(string query) { var stream = client.GetStream(); var readWriteBuffer = InternalMemoryPool.GetBuffer(); var writer = PacketWriter.Create(readWriteBuffer); ProtocolWriter.WritePrepareStatement(ref writer, query); var reader = SyncWriteAndRead(ref writer, 0, stream); // COM_STMT_PREPARE_OK on success, ERR_Packet otherwise if (reader.IsErrorPacket()) { throw ErrorPacket.Parse(ref reader).ToMySqlException(); } return(ProtocolReader.ReadStatementPrepareOk(ref reader)); }
public async Task Handle_DataMessage() { string correlationId = Guid.NewGuid().ToString(); const string message = @"FAFB070DABB7440780/KFM5KAIFA-METER 1-3:0.2.8(40) 0-0:1.0.0(000102045905W) 0 - 0:96.1.1(4530303033303030303030303032343133) 1 - 0:1.8.1(000181.011 * kWh) 1 - 0:1.8.2(000182.044 * kWh) 1 - 0:2.8.1(000281.099 * kWh) 1 - 0:2.8.2(000282.077 * kWh) 0 - 0:96.14.0(0001) 1 - 0:1.7.0(00.034 * kW) 1 - 0:2.7.0(00.000 * kW) 0 - 0:17.0.0(999.9 * kW) 0 - 0:96.3.10(1) 0 - 0:96.7.21(00073) 0 - 0:96.7.9(00020) 1 - 0:99.97.0(3)(0 - 0:96.7.19)(000124235657W)(0000003149 * s)(000124225935W)(0000000289 * s)(000101000001W)(2147483647 * s) 1 - 0:32.32.0(00005) 1 - 0:52.32.0(00006) 1 - 0:72.32.0(00001) 1 - 0:32.36.0(00000) 1 - 0:52.36.0(00000) 1 - 0:72.36.0(00000) 0 - 0:96.13.1() 0 - 0:96.13.0() 1 - 0:31.7.0(000 * A) 1 - 0:51.7.0(000 * A) 1 - 0:71.7.0(000 * A) 1 - 0:21.7.0(00.034 * kW) 1 - 0:22.7.0(00.000 * kW) 1 - 0:41.7.0(00.000 * kW) 1 - 0:42.7.0(00.000 * kW) 1 - 0:61.7.0(00.000 * kW) 1 - 0:62.7.0(00.000 * kW) 0 - 1:24.1.0(003) 0 - 1:96.1.0(4730303131303033303832373133363133) 0 - 1:24.2.1(000102043601W)(72869.839 * m3) 0 - 1:24.4.0(1)!583C"; var mini = new Mini(); var ctx = new QboxDataDumpContext(message, 16, "localhost", "::1", mini); var parserFactoryMock = new Mock <IParserFactory>(); var protocolReader = new ProtocolReader(_protocolReaderLoggerMock.Object, message.AsMemory()); var protocolReaderFactoryMock = new Mock <IProtocolReaderFactory>(); protocolReaderFactoryMock.Setup(pr => pr.Create(It.IsAny <ReadOnlyMemory <char> >())).Returns(protocolReader); var smartMeterCounterParser = new SmartMeterCounterParser(_smartMeterLoggerMock.Object, _validators); parserFactoryMock.Setup(pf => pf.GetParser(It.IsAny <string>())).Returns(new MiniR21(_miniLoggerMock.Object, protocolReaderFactoryMock.Object, smartMeterCounterParser)); var sut = new QboxNextDataHandler(correlationId, ctx, parserFactoryMock.Object, _counterStoreServiceMock.Object, _stateStoreServiceMock.Object, _dateMock.Object, _qboxNextDataHandlerLoggerMock.Object); var result = await sut.HandleAsync(); var resultAsText = result.Trim('\x02', '\x03'); resultAsText.Should().Be("FB18D6728000"); }
/// <summary> /// on connected as an asynchronous operation. /// </summary> /// <param name="connection">The new <see cref="T:Microsoft.AspNetCore.Connections.ConnectionContext" /></param> /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the connection lifetime. When the task completes, the connection is complete.</returns> public override async Task OnConnectedAsync(ConnectionContext connection) { this.context = connection; this.reader = connection.CreateReader(); this.writer = connection.CreateWriter(); SessionManager.Singleton.AcceptSession(connection, writer, this.protocol); //IConnectionHeartbeatFeature heartbeatFeature = connection.Features.Get<IConnectionHeartbeatFeature>(); //heartbeatFeature.OnHeartbeat(this.SendHeartbeat, null); while (true) { try { var result = await reader.ReadAsync(protocol); var message = result.Message; _logger.LogInformation("Received a message of {Length} bytes", message.Payload.Length); if (result.IsCompleted) { break; } await writer.WriteAsync(protocol, message); } catch (Exception ex) { _logger.LogError(ex.Message); connection.Abort(); break; } finally { reader.Advance(); } } }
public void WriteRequestAndReadResponse() { //var properties = new Hashtable() { { "port", 8080 } }; //var channel = new TcpChannel(properties, null, new SoapServerFormatterSinkProvider()); //if using SOAP via TCP, messageRequestStream must be SOAP format var channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel, false); var service = new ServiceClass(); ObjRef obj = RemotingServices.Marshal(service, "Remote"); var uri = "tcp://localhost:8080/Remote"; using (var client = new TcpClient()) { client.Connect("localhost", 8080); using (var stream = client.GetStream()) { var messageRequest = new MethodCall(new Header[] { new Header("__Uri", uri), new Header("__MethodName", "Do"), new Header("__MethodSignature", new Type[] { typeof(string) }), new Header("__TypeName", typeof(ServiceClass).AssemblyQualifiedName), new Header("__Args", new object[] { "Hi" }) }); var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest); var writer = new ProtocolWriter(stream); writer.WritePreamble(); writer.WriteMajorVersion(); writer.WriteMinorVersion(); writer.WriteOperation(TcpOperations.Request); writer.WriteContentDelimiter(TcpContentDelimiter.ContentLength); writer.WriteContentLength(messageRequestStream.Length); writer.WriteTransportHeaders(uri); writer.WriteBytes(messageRequestStream); var reader = new ProtocolReader(stream); Console.WriteLine("Preamble: {0}", reader.ReadPreamble()); Console.WriteLine("MajorVersion: {0}", reader.ReadMajorVersion()); Console.WriteLine("MinorVersion: {0}", reader.ReadMinorVersion()); var op = reader.ReadOperation(); Assert.AreEqual(TcpOperations.Reply, op); Console.WriteLine("Operation: {0}", op); Console.WriteLine("ContentDelimiter: {0}", reader.ReadContentDelimiter()); var length = reader.ReadContentLength(); Console.WriteLine("ContentLength: {0}", length); reader.ReadTransportHeaders(); var messageResponse = BinaryFormatterHelper.DeserializeObject(reader.ReadBytes(length)) as MethodResponse; Assert.IsNotNull(messageResponse); DumpHelper.DumpMessage(messageResponse); if (messageResponse.Exception != null) throw messageResponse.Exception; Assert.AreEqual("Hi", messageResponse.ReturnValue); } } }