public MessageWriter(TransportState transportState, NetworkStream networkStream) { _networkStream = networkStream; _transportState = transportState; _messageBuilder = new EncryptedMessageBuilder(transportState); }
private bool TryStop() { TransportState previousState = this.MoveToStateIfPossible(TransportState.Closed, TransportState.Error); switch (previousState) { case TransportState.Closed: case TransportState.Error: return(false); case TransportState.NotInitialized: case TransportState.Opening: this.connectCompletion.TrySetCanceled(); break; case TransportState.Open: case TransportState.Subscribing: this.subscribeCompletionSource.TrySetCanceled(); break; case TransportState.Receiving: this.disconnectAwaitersCancellationSource.Cancel(); break; default: Debug.Fail($"Unknown transport state: {previousState}"); throw new InvalidOperationException(); } return(true); }
private void ReadHead(byte[] bytes, int offset, int limit) { int bytesLen = limit - offset; int headLen = HeaderLength - m_bufferOffset; if (bytesLen >= headLen) { Buffer.BlockCopy(bytes, offset, m_headBuffer, m_bufferOffset, headLen); offset += headLen; if (BitConverter.IsLittleEndian) { Array.Reverse(m_headBuffer); } m_bodyLen = (int)BitConverter.ToUInt16(m_headBuffer, 0); m_bodyBuffer = new byte[m_bodyLen]; // Buffer.BlockCopy(_headBuffer, 0, _bodyBuffer, 0, HeaderLength); m_bufferOffset = 0;//HeaderLength; m_transportState = TransportState.ReadBody; if (offset < limit) { ProcessBytes(bytes, offset, limit); } } else { Buffer.BlockCopy(bytes, offset, m_headBuffer, m_bufferOffset, bytesLen); m_bufferOffset += bytesLen; } }
public Transporter(WebSocket socket, Action <byte[]> processer) { this.socket = socket; this.messageProcesser = processer; transportState = TransportState.readHead; WebSocketReceiver.instance.AddRecListener(socket.address, this); }
private void readBody(byte[] bytes, int offset, int limit) { int length = this.pkgLength + 4 - this.bufferOffset; if (offset + length <= limit) { this.writeBytes(bytes, offset, length, this.bufferOffset, this.buffer); offset += length; this.messageProcesser(this.buffer); this.bufferOffset = 0; this.pkgLength = 0; if (this.transportState != TransportState.closed) { this.transportState = TransportState.readHead; } if (offset >= limit) { return; } this.processBytes(bytes, offset, limit); } else { this.writeBytes(bytes, offset, limit - offset, this.bufferOffset, this.buffer); this.bufferOffset += limit - offset; this.transportState = TransportState.readBody; } }
private void ReadBody(byte[] bytes, int offset, int limit) { int bytesLen = limit - offset; int bodyLen = m_bodyLen - m_bufferOffset;//_bodyLen + HeaderLength - _bufferOffset; // if ((offset + bodyLen) <= limit) if (bytesLen >= bodyLen) { Buffer.BlockCopy(bytes, offset, m_bodyBuffer, m_bufferOffset, bodyLen); offset += bodyLen; if (SocketMessageEvent != null) { SocketMessageEvent(this, new SocketMessageEventArgs(m_bodyBuffer)); } m_bufferOffset = 0; m_bodyLen = 0; m_transportState = TransportState.ReadHead; if (offset < limit) { ProcessBytes(bytes, offset, limit); } } else { Buffer.BlockCopy(bytes, offset, m_bodyBuffer, m_bufferOffset, bytesLen); m_bufferOffset += bytesLen; } }
internal void close() { if (this.transportState == TransportState.closed) { return; } //Console.WriteLine("transporter close " + this.socket.Connected); this.socket.Close(); this.transportState = TransportState.closed; // // EndSend can only be called once per asynchronous operation // try { // global::UnityEngine.Debug.Log(socket.Connected); // // if(this.onReceiving) { // global::UnityEngine.Debug.Log ("EndReceive"); // socket.EndReceive (this.asyncReceive); // this.onReceiving = false; // } // if(this.onSending) { // global::UnityEngine.Debug.Log ("EndSend"); // socket.EndSend(this.asyncSend); // this.onSending = false; // } // } // catch (Exception e) { // this.onSending = false; // this.onReceiving = false; // global::UnityEngine.Debug.LogError ("Transporter close -> " + e.Message.ToString ()); // DebugInfo.Message (e.Message.ToString ()); // // Console.WriteLine(e.Message); // } }
public RavenFileSystem(InMemoryRavenConfiguration systemConfiguration, string name, TransportState receivedTransportState = null) { this.Name = name; this.systemConfiguration = systemConfiguration; this.transportState = receivedTransportState ?? new TransportState(); this.storage = CreateTransactionalStorage(systemConfiguration); this.sigGenerator = new SigGenerator(); this.fileLockManager = new FileLockManager(); this.BufferPool = new BufferPool(1024 * 1024 * 1024, 65 * 1024); this.conflictDetector = new ConflictDetector(); this.conflictResolver = new ConflictResolver(storage, new CompositionContainer(systemConfiguration.Catalog)); this.notificationPublisher = new NotificationPublisher(transportState); this.synchronizationTask = new SynchronizationTask(storage, sigGenerator, notificationPublisher, systemConfiguration); this.metricsCounters = new MetricsCountersManager(); this.search = new IndexStorage(name, systemConfiguration); this.conflictArtifactManager = new ConflictArtifactManager(storage, search); this.storageOperationsTask = new StorageOperationsTask(storage, search, notificationPublisher); AppDomain.CurrentDomain.ProcessExit += ShouldDispose; AppDomain.CurrentDomain.DomainUnload += ShouldDispose; }
private void ReadBody(byte[] bytes, int offset, int limit) { var length = _pkgLength - _bufferOffset; if ((offset + length) <= limit) { WriteBytes(bytes, offset, length, _bufferOffset, _buffer); offset += length; //Invoke the protocol api to handle the message _protocol.ProcessMessage(_buffer); _bufferOffset = 0; _pkgLength = 0; if (_transportState != TransportState.Closed) { _transportState = TransportState.ReadHead; } if (offset < limit) { ProcessBytes(bytes, offset, limit); } } else { WriteBytes(bytes, offset, limit - offset, _bufferOffset, _buffer); _bufferOffset += limit - offset; _transportState = TransportState.ReadBody; } }
public Transporter(Socket socket, Action <byte[]> processer) { HeadLength = 4; //TYPE,LENGTH this.socket = socket; this.messageProcesser = processer; transportState = TransportState.readHead; }
private void ReadHead(byte[] bytes, int offset, int limit) { var length = limit - offset; var headNum = HeadLength - _bufferOffset; if (length >= headNum) { //Write head buffer WriteBytes(bytes, offset, headNum, _bufferOffset, _headBuffer); //Get package length _pkgLength = _headBuffer[1] | (_headBuffer[0] << 8); //Init message buffer _buffer = new byte[_pkgLength]; offset += headNum; _transportState = TransportState.ReadBody; if (offset <= limit) { ProcessBytes(bytes, offset, limit); } } else { WriteBytes(bytes, offset, length, _bufferOffset, _headBuffer); _bufferOffset += length; } }
private bool readHead(byte[] bytes, int offset, int limit) { int length = limit - offset; int headNum = HeadLength - bufferOffset; if (length >= headNum) { //Write head buffer writeBytes(bytes, offset, headNum, bufferOffset, headBuffer); //Get package length pkgLength = (headBuffer [1] << 16) + (headBuffer [2] << 8) + headBuffer [3]; //Init message buffer buffer = new byte[HeadLength + pkgLength]; writeBytes(headBuffer, 0, HeadLength, buffer); offset += headNum; bufferOffset = HeadLength; this.transportState = TransportState.readBody; if (offset <= limit) { processBytes(bytes, offset, limit); } return(true); } else { writeBytes(bytes, offset, length, bufferOffset, headBuffer); bufferOffset += length; return(false); } }
bool TryStop() { TransportState previousState = this.MoveToStateIfPossible(TransportState.Closed, TransportState.Error); switch (previousState) { case TransportState.Closed: case TransportState.Error: return(false); case TransportState.NotInitialized: case TransportState.Opening: this.connectCompletion.TrySetCanceled(); break; case TransportState.Open: case TransportState.Subscribing: this.subscribeCompletionSource.TrySetCanceled(); break; case TransportState.Receiving: this.disconnectAwaitersCancellationSource.Cancel(); break; default: throw new ArgumentOutOfRangeException(); } return(true); }
private void readBody(byte[] bytes, int offset, int limit) { int length = pkgLength + HeadLength - bufferOffset; if ((offset + length) <= limit) { writeBytes(bytes, offset, length, bufferOffset, buffer); offset += length; //Invoke the protocol api to handle the message this.messageProcesser.Invoke(buffer); this.bufferOffset = 0; this.pkgLength = 0; if (this.transportState != TransportState.closed) { this.transportState = TransportState.readHead; } if (offset < limit) { processBytes(bytes, offset, limit); } } else { writeBytes(bytes, offset, limit - offset, bufferOffset, buffer); bufferOffset += limit - offset; this.transportState = TransportState.readBody; } }
public Transporter(Socket socket, Protocol protocol) { _socket = socket; _protocol = protocol; _transportState = TransportState.ReadHead; _bufferOffset = 0; _pkgLength = 0; }
public RavenFileSystem(InMemoryRavenConfiguration config, string name, TransportState receivedTransportState = null) { ExtensionsState = new AtomicDictionary <object>(); Name = name; ResourceName = string.Concat(Constants.FileSystem.UrlPrefix, "/", name); configuration = config; try { ValidateStorage(); configuration.Container.SatisfyImportsOnce(this); transportState = receivedTransportState ?? new TransportState(); storage = CreateTransactionalStorage(configuration); sigGenerator = new SigGenerator(); fileLockManager = new FileLockManager(); BufferPool = new BufferPool(1024 * 1024 * 1024, 65 * 1024); conflictDetector = new ConflictDetector(); conflictResolver = new ConflictResolver(storage, new CompositionContainer(configuration.Catalog)); notificationPublisher = new NotificationPublisher(transportState); synchronizationTask = new SynchronizationTask(storage, sigGenerator, notificationPublisher, configuration); metricsCounters = new MetricsCountersManager(); search = new IndexStorage(name, configuration); conflictArtifactManager = new ConflictArtifactManager(storage, search); TimerManager = new ResourceTimerManager(); Tasks = new TaskActions(this, Log); Files = new FileActions(this, Log); Synchronizations = new SynchronizationActions(this, Log); AppDomain.CurrentDomain.ProcessExit += ShouldDispose; AppDomain.CurrentDomain.DomainUnload += ShouldDispose; } catch (Exception e) { Log.ErrorException(string.Format("Could not create file system '{0}'", Name ?? "unknown name"), e); try { Dispose(); } catch (Exception ex) { Log.FatalException("Failed to dispose when already getting an error in file system ctor", ex); } throw; } }
public void ParseNotSupportedMessageTest() { TransportState transportState = new TransportState(); PingMessage referenceMessage = new PingMessage(0, 0); MessageReader messageReader = new MessageReader(transportState, new List <MessageDefinition> { InitMessage.MessageDefinition }, new List <IMessageValidator>()); Assert.Throws <MessageNotSupportedException>(() => messageReader.Parse(referenceMessage.GetBytes())); }
internal void close() { this.transportState = TransportState.closed; /*try{ if(this.onReceiving) socket.EndReceive (this.asyncReceive); if(this.onSending) socket.EndSend(this.asyncSend); }catch (Exception e){ Console.WriteLine(e.Message); }*/ }
public async void OnError(Exception exception) { try { TransportState previousState = this.MoveToStateIfPossible(TransportState.Error, TransportState.Closed); switch (previousState) { case TransportState.Error: case TransportState.Closed: return; case TransportState.NotInitialized: case TransportState.Opening: this.fatalException = exception; this.connectCompletion.TrySetException(exception); this.subscribeCompletionSource.TrySetException(exception); break; case TransportState.Open: case TransportState.Subscribing: this.fatalException = exception; this.subscribeCompletionSource.TrySetException(exception); break; case TransportState.Receiving: this.fatalException = exception; this.disconnectAwaitersCancellationSource.Cancel(); break; default: throw new ArgumentOutOfRangeException(); } await this.closeRetryPolicy.ExecuteAsync(this.CleanupAsync); // Codes_SRS_CSHARP_MQTT_TRANSPORT_28_04: If OnError is triggered after OpenAsync is called, onConnectionClosedCallback shall be invoked. // Codes_SRS_CSHARP_MQTT_TRANSPORT_28_05: If OnError is triggered after ReceiveAsync is called, onConnectionClosedCallback shall be invoked. // Codes_SRS_CSHARP_MQTT_TRANSPORT_28_06: If OnError is triggered without any prior operation, onConnectionClosedCallback shall not be invoked. // Codes_SRS_CSHARP_MQTT_TRANSPORT_28_07: If OnError is triggered in error state, onConnectionClosedCallback shall not be invoked. if ((previousState & TransportState.Open) == TransportState.Open) { await Task.Run(async() => await this.connectionClosedListener( this.channel, new ConnectionEventArgs { ConnectionType = ConnectionType.MqttConnection, ConnectionStatus = ConnectionStatus.Disconnected_Retrying, ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network })); } } catch (Exception ex) when(!ex.IsFatal()) { } }
/// <summary> /// Occurs when the transport is about to be disposed. /// </summary> /// <param name="disposing">Whether we are disposing or finalizing.</param> protected override void Dispose(bool disposing) { // Close the bound transport channel as well //if (this.Channel != null && this.Channel.IsRunning) // this.Channel.Close(); this.State = TransportState.Closed; // Call the base base.Dispose(disposing); }
internal void close() { this.transportState = TransportState.closed; /*try{ * if(this.onReceiving) socket.EndReceive (this.asyncReceive); * if(this.onSending) socket.EndSend(this.asyncSend); * }catch (Exception e){ * Console.WriteLine(e.Message); * }*/ }
internal void close() { this.transportState = TransportState.closed; if (this.onReceiving) { this.socket.EndReceive(this.asyncReceive); } if (this.onSending) { this.socket.EndSend(this.asyncSend); } }
public static TransportInfo Create(TransportState transportState) { var element = "<u:GetTransportInfoResponse xmlns:u=\"urn:schemas-upnp-org:service:AVTransport:1\">" + "<CurrentTransportState>{0}</CurrentTransportState>" + "<CurrentTransportStatus>OK</CurrentTransportStatus>" + "<CurrentSpeed>1</CurrentSpeed>" + "</u:GetTransportInfoResponse>"; element = string.Format(element, transportState); return(new TransportInfo(XElement.Parse(element))); }
private async void OnTransportStateChanged(TransportState state) { if (state == TransportState.ConnectionFailed) { await this.SoftCloseAsync().ConfigureAwait(false); } else if (state == TransportState.Closed) { if (this.State == XmppTransportState.Opening || this.State == XmppTransportState.Open) { await this.SoftCloseAsync().ConfigureAwait(false); } } }
private void state_StateComplete(object sender, EventArgs e) { graphics.Drawing = false; Thread.Sleep(100); if (state is TransportState) { TransportState s = (TransportState)state; if (s.ShipRectangle.X < 0) { beginLandGrant(); } else { beginSummary(); } } else if (state is SummaryState) { round++; if (round == 1) { beginTransport(TransportState.LocalState.Lifting); } else { beginLandGrant(); } } else if (state is LandGrantState) { playerTurn = 0; beginPlayerTurn(OrderedPlayers[playerTurn].PlayerNum); } else if (state is PlayerTurnState) { playerTurn++; if (playerTurn == players.Length) { } else { beginPlayerTurn(OrderedPlayers[playerTurn].PlayerNum); } } graphics.Drawing = true; }
public async Task WhenTransportIsNotConnected_ShouldGoStraightToClosed(TransportState transportState) { // Arrange _context.Transport = new FakeTransport() { State = transportState }; // Act await _state.OnAttachToContext(); // Assert _context.StateShouldBe <ConnectionClosedState>(); }
public async Task ConnectAsync(CancellationToken token) { using (await _stateAsyncLock.LockAsync(token)) { if (State == TransportState.Connected) { return; } var args = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(_ipAddress, _port) }; var awaitable = new SocketAwaitable(args); try { _packetNumber = 0; await _socket.ConnectAsync(awaitable); } catch (SocketException e) { Log.Debug(e); } catch (Exception e) { Log.Error(e); _state = TransportState.Disconnected; throw; } switch (args.SocketError) { case SocketError.Success: case SocketError.IsConnected: _state = TransportState.Connected; break; default: _state = TransportState.Disconnected; break; } if (_state != TransportState.Connected) { return; } _connectionCancellationTokenSource = new CancellationTokenSource(); _receiverTask = StartReceiver(_connectionCancellationTokenSource.Token); } }
public void BuildTest() { TransportState transportState = new TransportState(); transportState.SendEncryptionKey = "969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9".HexToByteArray(); EncryptedMessageBuilder encryptedMessageBuilder = new EncryptedMessageBuilder(transportState); byte[] result1 = encryptedMessageBuilder.Build("68656c6c6f".HexToByteArray()); Assert.Equal("cf2b30ddf0cf3f80e7c35a6e6730b59fe802473180f396d88a8fb0db8cbcf25d2f214cf9ea1d95", result1.ToHex()); byte[] result2 = encryptedMessageBuilder.Build("1234567890".HexToByteArray()); Assert.Equal("72887022101f0b6753e0c7de21657d35a4cb504e66cad96173c643306b2ea8a5ff3145ccdfc570", result2.ToHex()); }
public void ParseTest() { TransportState transportState = new TransportState(); byte[] globalFeatures = { 0, 5 }; byte[] localFeatures = { 0, 6 }; InitMessage referenceMessage = new InitMessage(globalFeatures, localFeatures); MessageReader messageReader = new MessageReader(transportState, new List <MessageDefinition> { InitMessage.MessageDefinition }, new List <IMessageValidator>()); Message message = messageReader.Parse(referenceMessage.GetBytes()); Assert.IsType <InitMessage>(message); Assert.Equal(globalFeatures, ((InitMessage)message).Globalfeatures); Assert.Equal(localFeatures, ((InitMessage)message).Localfeatures); }
public void ReadMultipleTest() { TransportState transportState = new TransportState(); transportState.ReceiveDecryptionKey = "969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9".HexToByteArray(); EncryptedMessageReader messageReader = new EncryptedMessageReader(transportState); byte[] cipherData = "cf2b30ddf0cf3f80e7c35a6e6730b59fe802473180f396d88a8fb0db8cbcf25d2f214cf9ea1d9572887022101f0b6753e0c7de21657d35a4cb504e66cad96173c643306b2ea8a5ff3145ccdfc570".HexToByteArray(); (List <byte[]> actual, int totalRead) = messageReader.Read(cipherData, cipherData.Length); Assert.Equal(78, totalRead); Assert.Equal(2, actual.Count); Assert.Equal("68656c6c6f", actual[0].ToHex()); Assert.Equal("1234567890", actual[1].ToHex()); }
public RavenFileSystem(InMemoryRavenConfiguration systemConfiguration, TransportState transportState, string name) { this.Name = name; this.systemConfiguration = systemConfiguration; var storageType = systemConfiguration.DefaultFileSystemStorageTypeName; if (string.Equals(InMemoryRavenConfiguration.VoronTypeName, storageType, StringComparison.OrdinalIgnoreCase) == false) { if (Directory.Exists(systemConfiguration.FileSystemDataDirectory) && Directory.EnumerateFileSystemEntries(systemConfiguration.FileSystemDataDirectory).Any()) { throw new InvalidOperationException( string.Format( "We do not allow to run on a storage engine other then Voron, while we are in the early pre-release phase of RavenDB 3.0. You are currently running on {0}", storageType)); } Trace.WriteLine("Forcing filesystem to run on Voron - pre release behavior only, mind " + Path.GetFileName(Path.GetDirectoryName(systemConfiguration.FileSystemDataDirectory))); storageType = InMemoryRavenConfiguration.VoronTypeName; } storage = CreateTransactionalStorage(storageType, systemConfiguration); search = new IndexStorage(systemConfiguration.FileSystemIndexStoragePath, systemConfiguration.Settings); sigGenerator = new SigGenerator(); var replicationHiLo = new SynchronizationHiLo(storage); var sequenceActions = new SequenceActions(storage); this.transportState = transportState; notificationPublisher = new NotificationPublisher(transportState); fileLockManager = new FileLockManager(); storage.Initialize(); search.Initialize(); var uuidGenerator = new UuidGenerator(sequenceActions); historian = new Historian(storage, replicationHiLo, uuidGenerator); BufferPool = new BufferPool(1024 * 1024 * 1024, 65 * 1024); conflictArtifactManager = new ConflictArtifactManager(storage, search); conflictDetector = new ConflictDetector(); conflictResolver = new ConflictResolver(); synchronizationTask = new SynchronizationTask(storage, sigGenerator, notificationPublisher, systemConfiguration); storageOperationsTask = new StorageOperationsTask(storage, search, notificationPublisher); metricsCounters = new MetricsCountersManager(); AppDomain.CurrentDomain.ProcessExit += ShouldDispose; AppDomain.CurrentDomain.DomainUnload += ShouldDispose; }
public void update() { if(this.transportState == TransportState.connect) { try { if(this.socket.Poll(-1, SelectMode.SelectWrite)) { this.transportState = TransportState.readHead; if(this.onConnect != null) this.onConnect(); } } catch(SocketException e) { if(e.ErrorCode == WSAEWOULDBLOCK) { Debug.Log("Waiting for Socket to finish connecting..."); } else { Debug.Log("SocketException, code: " + e.ErrorCode); close(); } } } else if(this.transportState != TransportState.closed) { this.receive(); } }
public IQueryable<TransportModel> FindTransportBy(TransportState state) { return transportRepository.FindBy(state); }
public IQueryable<TransportModel> FindAllTransportsExcept(TransportState state) { return transportRepository.FindAllExcept(state); }
internal void close() { this.transportState = TransportState.closed; if(this.onReceiving) socket.EndReceive (this.asyncReceive); if(this.onSending) socket.EndSend(this.asyncSend); }
public Transporter(Socket socket, Action<byte[]> processer) { this.socket = socket; this.messageProcesser = processer; transportState = TransportState.readHead; }
private bool readHead(byte[] bytes, int offset, int limit) { int length = limit - offset; int headNum = HeadLength - bufferOffset; if(length >= headNum){ //Write head buffer writeBytes(bytes, offset, headNum, bufferOffset, headBuffer); //Get package length pkgLength = (headBuffer [1] << 16) + (headBuffer [2] << 8) + headBuffer [3]; //Init message buffer buffer = new byte[HeadLength + pkgLength]; writeBytes (headBuffer, 0, HeadLength, buffer); offset += headNum; bufferOffset = HeadLength; this.transportState = TransportState.readBody; if(offset <= limit) processBytes(bytes, offset, limit); return true; }else{ writeBytes(bytes, offset, length, bufferOffset, headBuffer); bufferOffset += length; return false; } }
bool TryStateTransition(TransportState fromState, TransportState toState) { return (TransportState)Interlocked.CompareExchange(ref this.state, (int)toState, (int)fromState) == fromState; }
internal void close() { if(this.transportState != TransportState.closed) { this.transportState = TransportState.closed; if(this.onDisconnect != null) { this.onDisconnect(); } } }
private void readBody(byte[] bytes, int offset, int limit) { int length = pkgLength + HeadLength - bufferOffset; if ((offset + length) <= limit) { writeBytes (bytes, offset, length, bufferOffset, buffer); offset += length; //Invoke the protocol api to handle the message this.messageProcesser.Invoke(buffer); this.bufferOffset = 0; this.pkgLength = 0; if(this.transportState != TransportState.closed) this.transportState = TransportState.readHead; if(offset< limit) processBytes(bytes, offset, limit); } else { writeBytes (bytes, offset, limit - offset, bufferOffset, buffer); bufferOffset += limit - offset; this.transportState = TransportState.readBody; } }
TransportState MoveToStateIfPossible(TransportState destination, TransportState illegalStates) { TransportState previousState = this.State; do { if ((previousState & illegalStates) > 0) { return previousState; } TransportState prevState; if ((prevState = (TransportState)Interlocked.CompareExchange(ref this.state, (int)destination, (int)previousState)) == previousState) { return prevState; } previousState = prevState; } while (true); }