public void Send(IReadOnlyList <IMessage> messages, INetworkStream outputStream) { log.Debug($"Send {messages.Count} message(s) to {outputStream}"); bool isFirst = true; foreach (var msg in messages) { var serialized = serializer.Serialize(msg); if (!isFirst) { outputStream.Write(Separator, 0, Separator.Length); } outputStream.Write(serialized, 0, serialized.Length); isFirst = false; } }
//------------------------------------------------------------------------------ // // Method: EncodeAndSend // //------------------------------------------------------------------------------ /// <summary> /// Adds delimiter characters and header information to the specified message and sends it. /// </summary> /// <param name="message">The message to send.</param> private void EncodeAndSend(string message) { byte[] messageByteArray = stringEncoding.GetBytes(message); // Create a 4 byte message sequence number, and encode as little endian byte[] messageSequenceNumberByteArray = BitConverter.GetBytes(messageSequenceNumber); EncodeAsLittleEndian(messageSequenceNumberByteArray); // Create 8 bytes containing the length of the message body, and encode as little endian byte[] messageSizeHeader = BitConverter.GetBytes(messageByteArray.LongLength); EncodeAsLittleEndian(messageSizeHeader); // Encode the message byte[] encodedMessageByteArray = new byte[messageSequenceNumberByteArray.Length + messageSizeHeader.Length + messageByteArray.Length + 2]; encodedMessageByteArray[0] = messageStartDelimiter; Array.Copy(messageSequenceNumberByteArray, 0, encodedMessageByteArray, 1, messageSequenceNumberByteArray.Length); Array.Copy(messageSizeHeader, 0, encodedMessageByteArray, 1 + messageSequenceNumberByteArray.Length, messageSizeHeader.Length); Array.Copy(messageByteArray, 0, encodedMessageByteArray, 1 + messageSequenceNumberByteArray.Length + messageSizeHeader.Length, messageByteArray.Length); encodedMessageByteArray[encodedMessageByteArray.Length - 1] = messageEndDelimiter; // Send the message INetworkStream networkStream = client.GetStream(); networkStream.Write(encodedMessageByteArray, 0, encodedMessageByteArray.Length); // As per http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.flush%28v=vs.80%29.aspx the Flush() method has no effect on NetworkStream objects, and hence is not called. WaitForMessageAcknowledgement(networkStream); }
public void PingHandler(INetworkStream stream) { var buffer = new byte[PingSize]; using (var timer = new Timer(_ => { stream.Dispose(); }, null, TimeSpan.Zero, PingTimeout)) { while (true) { if (stream?.ReadFull(buffer) != buffer.Length) { break; } if (stream?.Write(buffer, 0, buffer.Length) != buffer.Length) { break; } timer.Change(TimeSpan.Zero, PingTimeout); } } }
private TimeSpan Ping(INetworkStream stream) { var buffer = new byte[PingSize]; using (var rng = RandomNumberGenerator.Create()) { rng.GetNonZeroBytes(buffer); } var sw = new Stopwatch(); sw.Start(); if (stream.Write(buffer, 0, buffer.Length) != buffer.Length) { return(TimeSpan.Zero); } var rbuf = new byte[PingSize]; if (stream.ReadFull(rbuf) != rbuf.Length) { return(TimeSpan.Zero); } if (!rbuf.SequenceEqual(buffer)) { return(TimeSpan.Zero); } sw.Stop(); return(sw.Elapsed); }
public bool Write(byte[] transmitArray) { bool ret = false; if (serverNetworkStream != null) { serverNetworkStream.Write(transmitArray, 0, transmitArray.Length); serverNetworkStream.Flush(); ret = true; } return(ret); }
public void GivenAFakedSocketACallToWriteShouldBeRelayed() { string writtenString = Guid.NewGuid().ToString(); ISocket socket = A.Fake <ISocket>(); INetworkStream stream = A.Fake <INetworkStream>(); A.CallTo(() => socket.GetStream()).Returns(stream); TcpByteStream sut = new TcpByteStream(socket); sut.Write(writtenString); A.CallTo(() => stream.Write(A <byte[]> .Ignored, 0, writtenString.Length)).MustHaveHappened(); }
/// <summary> /// /// </summary> /// <param name="requests">Requests to send</param> /// <returns>Responses from the server</returns> public Message[] SendRequests(Message[] requests) { byte[] requestsBytes; int count = _converter.MessagesToBytes(out requestsBytes, requests); ITcpClient _tcpClient = _tcpFactory.Create(); _tcpClient.Connect(_address, _port); using (INetworkStream networkStream = _tcpClient.GetStream()) { networkStream.Write(requestsBytes, count); byte[] responseBytes = new byte[Properties.Settings.Default.MaxBufferSize]; int len = networkStream.Read(responseBytes, Properties.Settings.Default.MaxBufferSize); networkStream.Close(); _tcpClient.Close(); return(_converter.BytesToMessages(responseBytes, len)); } }
/// <summary> /// Send a command to the Folding@Home client server. /// </summary> /// <param name="command">Command text. Null, empty, or whitespace strings will be ignored.</param> /// <exception cref="InvalidOperationException">Connection is not connected.</exception> /// <remarks>Callers should make sure the Connection is connected by checking the value of the Connected property.</remarks> public void SendCommand(string command) { // check connection status, callers should make sure they're connected first if (!Connected) { throw new InvalidOperationException("Connection is not connected."); } if (command == null || command.Trim().Length == 0) { OnStatusMessage(new StatusMessageEventArgs("No command text given.", TraceLevel.Warning)); return; } if (!command.EndsWith("\n", StringComparison.Ordinal)) { command += "\n"; } byte[] buffer = Encoding.ASCII.GetBytes(command); #if SEND_ASYNC _stream.BeginWrite(buffer, 0, buffer.Length, WriteCallback, new AsyncData(command, buffer)); #else try { _stream.Write(buffer, 0, buffer.Length); // send data sent event OnDataLengthSent(new DataLengthEventArgs(buffer.Length)); // send status message OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Sent command: {0} ({1} bytes)", CleanUpCommandText(command), buffer.Length), TraceLevel.Info)); } catch (Exception ex) { OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Write failed: {0}", ex.Message), TraceLevel.Error)); Close(); } #endif }
private void WriteOnStream(byte[] buffer, int toWrite) { CheckAndResize(ref buffer, toWrite); browserStream.Write(buffer, 0, toWrite); }
protected void Send(string value, ITcpClient tcpClient) { value += EndOfLine; INetworkStream networkStream = default; byte[] bytes = default; try { ThrowIf.IsNull(tcpClient, "Error in Send(). tcpClient can't be null!"); try { bytes = Encoding.ASCII.GetBytes(value); } catch (Exception exception) { if (!Disconnecting) { throw new TcpIpGetBytesFailedException(exception); } } try { networkStream = tcpClient.GetStream(); } catch (Exception exception) { if (!Disconnecting) { throw new TcpIpGetStreamFailedException(exception); } } if (networkStream.CanWrite) { try { networkStream.Write(bytes, 0, bytes.Length); } catch (Exception exception) { if (!Disconnecting) { throw new TcpIpNetworkStreamWriteFailedException(exception); } } } else { if (!Disconnecting) { throw new TcpIpNetworkStreamIsNotWriteableException(); } } } catch (Exception exception) { if (!Disconnecting) { throw new TcpIpSendFailedException(exception); } } }
public void Send(IMessage message, INetworkStream outputStream) { var serialized = serializer.Serialize(message); outputStream.Write(serialized, 0, serialized.Length); }