WriteAsync() public method

public WriteAsync ( byte buffer, int offset, int size, CancellationToken cancellationToken ) : System.Threading.Task
buffer byte
offset int
size int
cancellationToken System.Threading.CancellationToken
return System.Threading.Task
コード例 #1
2
ファイル: RemoteSender.cs プロジェクト: holinov/BitSharp
        public async Task SendMessageAsync(Message message)
        {
            try
            {
                await semaphore.DoAsync(async () =>
                {
                    using (var stream = new NetworkStream(this.socket))
                    {
                        var stopwatch = new Stopwatch();
                        stopwatch.Start();

                        var byteStream = new MemoryStream();
                        NetworkEncoder.EncodeMessage(byteStream, message);

                        var messageBytes = byteStream.ToArray();
                        await stream.WriteAsync(messageBytes, 0, messageBytes.Length);

                        stopwatch.Stop();
                        //Debug.WriteLine("-------------------------");
                        //Debug.WriteLine(string.Format("Sent {0} in {1} ms\nPayload: {2}", message.Command, stopwatch.ElapsedMilliseconds, message.Payload.ToHexDataString()));
                    }
                });
            }
            catch (Exception e)
            {
                Fail(e);
            }
        }
コード例 #2
0
        private async Task AuthenticateV5(NetworkStream stream, CancellationToken cancellationToken)
        {
            await stream.WriteAsync(new byte[] { 5, 2, 0, 2 }, 0, 4, cancellationToken);

            switch ((await ReadBytes(stream, 2, cancellationToken)).Last())
            {
                case 0:
                    break;
                case 2:
                    await stream.WriteAsync(new byte[] { 1, 0, 0 }, 0, 3, cancellationToken);
                    byte[] buffer = new byte[2];
                    int received = 0;
                    while (received != 2)
                    {
                        received += await stream.ReadAsync(buffer, received, 2 - received, cancellationToken);
                    }

                    if (buffer[1] != 0)
                    {
                        throw new SocksRequestFailedException("Authentication failed");
                    }
                    break;
                case 255:
                    throw new SocksRequestFailedException("No authentication method accepted.");
                default:
                    throw new SocksRequestFailedException();
            }
        }
コード例 #3
0
        public async Task <bool> Send(byte[] data)
        {
            if (!disposed)
            {
                if (m_Client.Connected)
                {
                    byte[] dataToSend = new byte[data.Length + 8];
                    Array.Copy(BitConverter.GetBytes(dataToSend.Length), dataToSend, 4);                  // PackageLength
                    Array.Copy(data, 0, dataToSend, 4, data.Length);                                      // Messages
                    Array.Copy(new byte[] { 0xCC, 0xCC, 0xCC, 0xCC }, 0, dataToSend, data.Length + 4, 4); // PostAmble

                    try
                    {
                        await m_Socket.WriteAsync(dataToSend, 0, dataToSend.Length);
                    }
                    catch (Exception)
                    {
                        disposed = true;
                    }

                    return(true);
                }
            }
            return(false);
        }
コード例 #4
0
        public async Task V5(NetworkStream stream, Uri uri, CancellationToken cancellationToken)
        {
            await AuthenticateV5(stream, cancellationToken);

            byte[] data = new byte[10] { 5, 1, 0, 1, 0, 0, 0, 0, 0, 0 };

            Array.Copy(GetIpAddress(uri.Host).GetAddressBytes(), 0, data, 4, 4);
            Array.Copy(PortToBytes((ushort)uri.Port), 0, data, 8, 2);

            await stream.WriteAsync(data, 0, data.Length, cancellationToken);
            byte[] buffer = await ReadBytes(stream, 4, cancellationToken);
            if (buffer[1] != 0)
            {
                throw new SocksRequestFailedException();
            }
            switch (buffer[3])
            {
                case 1:
                    await ReadBytes(stream, 6, cancellationToken);
                    break;
                case 3:
                    await ReadBytes(stream, (await ReadBytes(stream, 1, cancellationToken)).Single() + 2, cancellationToken);
                    break;
                case 4:
                    await ReadBytes(stream, 18, cancellationToken);
                    break;
                default:
                    throw new SocksRequestFailedException();
            }
        }
コード例 #5
0
 async Task handleNetworkStream(NetworkStream stream)
 {
     var buffer = new byte[bufferSize];
     while (true)
     {
         if (!await fill(stream, buffer, headerSize).ConfigureAwait(false))
         {
             Interlocked.Increment(ref CloseByInvalidStream);
             return;
         }
         var length = BitConverter.ToInt32(buffer, 0);
         if (length == 0)
         {
             Interlocked.Increment(ref CloseByPeerCount);
             return;
         }
         if (!await fill(stream, buffer, length).ConfigureAwait(false))
         {
             Interlocked.Increment(ref CloseByInvalidStream);
             return;
         }
         await stream.WriteAsync(buffer, 0, length).ConfigureAwait(false);
         Interlocked.Increment(ref WriteCount);
     }
 }
コード例 #6
0
ファイル: ProxyServer.cs プロジェクト: noricube/IRCProxy
        /// <summary>
        /// input stream에 있는 문자열을 output stream에 맞도록 변환하여 전달한다
        /// 만약 stream이 연결이 끊켰을 경우 false를 반환한다
        /// 에러가 난 경우 무시한다.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="input_codepage"></param>
        /// <param name="output_codepage"></param>
        /// <returns></returns>
        protected async Task<bool> ConvertStream(NetworkStream input, NetworkStream output, int input_codepage, int output_codepage)
        {
            byte[] buf = new byte[8196];

            int read_bytes = await input.ReadAsync(buf, 0, 8196);

            if (read_bytes == 0)
            {
                return false;
            }

            try
            {
                string converted_string = Encoding.GetEncoding(input_codepage).GetString(buf, 0, read_bytes);
                byte[] converted_buf = Encoding.GetEncoding(output_codepage).GetBytes(converted_string);
                await output.WriteAsync(converted_buf, 0, converted_buf.Count());
            }
            catch (Exception e)
            {
                // 인코딩 변환 실패는 에러만 출력하고 그냥 무시한다.
                Console.WriteLine("ConvertStream Fail: " + e.Message);

                return true;
            }
            return true;
        }
コード例 #7
0
ファイル: TcpServerActor.cs プロジェクト: gderham/fixity
        public void AcceptingMessagesFromClient()
        {
            Receive<SendMessage>(message => // Send message text to the client as ASCII.
            {
                byte[] buffer = Encoding.ASCII.GetBytes(message.Text);
                _tcpStream = _tcpClient.GetStream();
                _tcpStream.WriteAsync(buffer, 0, buffer.Length);
            });

            Receive<WaitForNextChunk>(message =>
            {
                var buffer = new byte[BufferSize];

                _tcpStream.ReadAsync(buffer, 0, BufferSize).ContinueWith(task =>
                {
                    if (task.Status == TaskStatus.Faulted)
                    {
                        // This happens if the socket is closed server side.
                        return null;
                    }
                    //TODO: Check for other error states before reading the result

                    int bytesReceived = task.Result;
                    // Note here we start with the previously received chunk.
                    var text = message.Buffer + Encoding.ASCII.GetString(buffer, 0, bytesReceived);

                    return new ReceivedChunk(text);
                },
                TaskContinuationOptions.AttachedToParent &
                TaskContinuationOptions.ExecuteSynchronously)
                .PipeTo(Self);
            });

            Receive<ReceivedChunk>(message =>
            {
                // Check if we have a complete message, if so send to client (who?)
                MessageInfo info = _messageSplitter(message.Text);

                // We received some bytes which contains (possibly multiple) messages.
                foreach (string msg in info.CompleteMessages)
                {
                    _listener.Tell(new ReceivedMessage(msg));
                }

                // And possibly also received a partial message at the end,
                // in which case we keep it to prefix the subsequently
                // received data.
                if (info.RemainingText != null)
                {
                    Self.Tell(new WaitForNextChunk(info.RemainingText));
                }
            });

            Receive<Shutdown>(message =>
            {
                BecomeShutDown();
            });
        }
コード例 #8
0
        public async Task<long> WriteAsync(Stream input, TcpResponseHeader header = null)
        {
            var stream = new NetworkStream(_socket);

            var len = input.Length - input.Position;

            if (header == null) header = new TcpResponseHeader(() => len);

            var head = header.GetBytes();

            await stream.WriteAsync(head, 0, head.Length);

            await input.CopyToAsync(stream, _writeBuffer.Length);

            return len + head.Length;
        }
コード例 #9
0
 public static async Task Sender(NetworkStream stream, CancellationTokenSource cts)
 {
     WriteLine("Sender task");
     while (true)
     {
         WriteLine("enter a string to send, shutdown to exit");
         string line = ReadLine();
         byte[] buffer = Encoding.UTF8.GetBytes($"{line}\r\n");
         await stream.WriteAsync(buffer, 0, buffer.Length);
         await stream.FlushAsync();
         if (string.Compare(line, "shutdown", ignoreCase: true) == 0)
         {
             cts.Cancel();
             WriteLine("sender task closes");
             break;
         }
     }
 }
コード例 #10
0
    public static async Task SendMsg(object message, NetworkStream stream)
    {
        MemoryStream memstm = new MemoryStream();
        BinaryFormatter fmtr = new BinaryFormatter();
        memstm.Seek(MSG_HDR_SIZE, SeekOrigin.Begin);
        // serialize object graph to stream
        fmtr.Serialize(memstm, message);
        // get the buffer from the memory stream
        byte[] membuf = memstm.ToArray();
        // get the byte array with the message size
        byte[] lenbuf = BitConverter.GetBytes(membuf.Length);
        // copy the length to the first four bytes of the message
        for (int i = 0; i < lenbuf.Length; i++)
            membuf[i] = lenbuf[i];
        // send the message synchronously
        await stream.WriteAsync(membuf, 0, membuf.Length);

    }
コード例 #11
0
        public async Task V4(NetworkStream stream, Uri uri, CancellationToken cancellationToken)
        {
            try
            {
                byte[] data = new byte[9] { 4, 1, 0, 0, 0, 0, 0, 0, 0 };

                Array.Copy(PortToBytes((ushort) uri.Port), 0, data, 2, 2);
                Array.Copy(GetIpAddress(uri.Host).GetAddressBytes(), 0, data, 4, 4);

                await stream.WriteAsync(data, 0, data.Length, cancellationToken);

                if ((await ReadBytes(stream, 8, cancellationToken))[1] != 90)
                {
                    throw new SocksRequestFailedException("Negotiation failed.");
                }
            }
            catch
            {
                throw new SocksRequestFailedException();
            }
        }
コード例 #12
0
		/// <summary>
		/// Connect to the EV3 brick.
		/// </summary>
		/// <returns></returns>
		public async Task ConnectAsync()
		{
			_client = new TcpClient();
			await _client.ConnectAsync(_address, 5555);
			_stream = _client.GetStream();

			// unlock the brick (doesn't actually need serial number?)
			byte[] buff = Encoding.UTF8.GetBytes(UnlockCommand);
			await _stream.WriteAsync(buff, 0, buff.Length);

			// read the "Accept:EV340\r\n\r\n" response
			int read = await _stream.ReadAsync(buff, 0, buff.Length);
			string response = Encoding.UTF8.GetString(buff, 0, read);
			if(string.IsNullOrEmpty(response))
				throw new Exception("LEGO EV3 brick did not respond to the unlock command.");

			_tokenSource = new CancellationTokenSource();

			Task t = Task.Factory.StartNew(async () =>
			{
				while(!_tokenSource.IsCancellationRequested)
				{
					// if the stream is valid and ready
					if(_stream != null && _stream.CanRead)
					{
						await _stream.ReadAsync(_sizeBuffer, 0, _sizeBuffer.Length);

						short size = (short)(_sizeBuffer[0] | _sizeBuffer[1] << 8);
						if(size == 0)
							return;

						byte[] report = new byte[size];
						await _stream.ReadAsync(report, 0, report.Length);
						if (ReportReceived != null)
							ReportReceived(this, new ReportReceivedEventArgs { Report = report });
					}
				}
			}, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
		}
コード例 #13
0
		public async Task<HttpListenerWebSocketContext> AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval)
		{
			if (subProtocol != null && subProtocol == "") {
				throw new ArgumentException ("subProtocol must not empty string");
			}
			if (receiveBufferSize < 16 || receiveBufferSize > 64 * 1024) {
				throw new ArgumentOutOfRangeException ("receiveBufferSize should be >=16 and <=64K bytes");
			}
			if (!request.IsWebSocketRequest) {
				throw new WebSocketException ("Request is not WebSocket Handshake");
			}
			string secKey = request.Headers ["Sec-WebSocket-Key"];
			if (secKey == null) {
				throw new WebSocketException ("Request doesn't contain Sec-WebSocket-Key header");
			}
			string acceptKey = StreamWebSocket.CreateAcceptKey (secKey);
			ArraySegment<byte> preloaded;
			var stream = new NetworkStream (cnc.Hijack (out preloaded));
			string header = "HTTP/1.1 101 Switching Protocols\r\n" +
				"Upgrade: websocket\r\n" +
				"Connection: Upgrade\r\n" +
				"Sec-WebSocket-Accept: " + acceptKey + "\r\n\r\n";
			var headerBytes = Encoding.ASCII.GetBytes (header);
			await stream.WriteAsync (headerBytes, 0, headerBytes.Length);
			var ws = new StreamWebSocket (stream, stream, null, subProtocol, false, preloaded);
			return new HttpListenerWebSocketContext (ws, request, user);
		}
コード例 #14
0
ファイル: KafkaTcpSocket.cs プロジェクト: jsifantu/kafka-net
        private async Task ProcessSentTasksAsync(NetworkStream netStream, SocketPayloadSendTask sendTask)
        {
            if (sendTask == null) return;

            using (sendTask)
            {
                var failed = false;
                var sw = Stopwatch.StartNew();
                try
                {
                    sw.Restart();
                    StatisticsTracker.IncrementGauge(StatisticGauge.ActiveWriteOperation);

                    if (OnWriteToSocketAttempt != null) OnWriteToSocketAttempt(sendTask.Payload);
                    await netStream.WriteAsync(sendTask.Payload.Buffer, 0, sendTask.Payload.Buffer.Length).ConfigureAwait(false);

                    sendTask.Tcp.TrySetResult(sendTask.Payload);
                }
                catch (Exception ex)
                {
                    failed = true;
                    if (_disposeToken.IsCancellationRequested)
                    {
                        var exception = new ObjectDisposedException("Object is disposing.");
                        sendTask.Tcp.TrySetException(exception);
                        throw exception;
                    }

                    sendTask.Tcp.TrySetException(ex);
                    throw;
                }
                finally
                {
                    StatisticsTracker.DecrementGauge(StatisticGauge.ActiveWriteOperation);
                    StatisticsTracker.CompleteNetworkWrite(sendTask.Payload, sw.ElapsedMilliseconds, failed);
                }
            }
        }
コード例 #15
0
        private static async Task CommunicateWithClientUsingNetworkStreamAsync(Socket socket)
        {
            try
            {
                using (var stream = new NetworkStream(socket, ownsSocket: true))
                {

                    bool completed = false;
                    do
                    {
                        byte[] readBuffer = new byte[1024];
                        int read = await stream.ReadAsync(readBuffer, 0, 1024);
                        string fromClient = Encoding.UTF8.GetString(readBuffer, 0, read);
                        WriteLine($"read {read} bytes: {fromClient}");
                        if (string.Compare(fromClient, "shutdown", ignoreCase: true) == 0)
                        {
                            completed = true;
                        }

                        byte[] writeBuffer = Encoding.UTF8.GetBytes($"echo {fromClient}");

                        await stream.WriteAsync(writeBuffer, 0, writeBuffer.Length);

                    } while (!completed);
                }
                WriteLine("closed stream and client socket");
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
コード例 #16
0
 public async Task writeMessageAsync(NetworkStream stream, string message, CancellationToken cancelToken, bool addDefaultMessageType = false)
 {
     byte[] msg;
     if (addDefaultMessageType)
         msg = Encoding.ASCII.GetBytes("<" + m_defaultMessageType + ">" + message + "</" + m_defaultMessageType + ">");
     else
         msg = Encoding.ASCII.GetBytes(message);
     try
     {
         await stream.WriteAsync(msg, 0, msg.Length,cancelToken);
     }
     catch(OperationCanceledException)
     {
         logMessage("Write operation cancelled");
     }
     catch(Exception ex)
     {
         logMessage("Unhandled exception in writeMessageAsync");
         logMessage(ex.ToString());
     }
 }
コード例 #17
0
        public async Task ClientSend(NetworkStream networkStream ,ServerClientMsg objectToClient)
        {
            var xmlSerializer = new XmlSerializer(objectToClient.GetType());

            StringBuilder SerializedSb = new StringBuilder();

            using (var stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, objectToClient);
                SerializedSb.Append(stringWriter.ToString());
            }

            var serializedString = SerializedSb.ToString();
            var MsgToSend = Encoding.UTF8.GetBytes(serializedString);
            await networkStream.WriteAsync(MsgToSend, 0, MsgToSend.Length);
        }
コード例 #18
0
        public async Task WriteToStreamAsync(NetworkStream stream)
        {
            byte[] packet = new byte[TotalPacketSize];
            
            BitConverter.GetBytes(PacketSize).CopyTo(packet, 0);
            BitConverter.GetBytes((int)Opcode).CopyTo(packet, 4);
            BitConverter.GetBytes((int)Type).CopyTo(packet, 8);
            Data.CopyTo(packet, 12);
            packet[packet.Length - 1] = ((byte)0x00);

            Console.WriteLine("Sent {0}", DataAsString());
            await stream.WriteAsync(packet, 0, TotalPacketSize);
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: Hotallday/xat-mitm
 public static async void Send(NetworkStream stream, string message) {
     try {
         var data = Encoding.UTF8.GetBytes(message);
         await stream.WriteAsync(data, 0, data.Length);
         WriteLine($"[INFO] - Send packet -> {message}");
     } catch (Exception) {
         WriteLine("[ERROR] - If you're having errors connecting, please reload the ixat.");
     }
 }
コード例 #20
0
        public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            _state = WebSocketState.Connecting;

            await _connection.ConnectAsync(uri.Host, uri.Port);

            _stream = _connection.GetStream();

            var secKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Substring(0, 16)));
            var expectedAccept = HandshakeHelpers.CreateResponseKey(secKey);

            var headerString =
                $"GET {uri.PathAndQuery} HTTP/1.1\r\n" +
                $"Host: {uri.Host}\r\n" +
                "Connection: Upgrade\r\n" +
                "Upgrade: websocket\r\n" +
                "Sec-WebSocket-Version: 13\r\n" +
                $"Sec-WebSocket-Protocol: {_subProtocol}\r\n" +
                $"Sec-WebSocket-Key: {secKey}\r\n\r\n";

            var bytes = Encoding.UTF8.GetBytes(headerString);
            await _stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
            await _stream.FlushAsync(cancellationToken);

            var buffer = new byte[1024];
            var resultLenth = await _stream.ReadAsync(buffer, 0, 1024, cancellationToken);
            var resultString = new StringReader(Encoding.UTF8.GetString(buffer, 0, resultLenth));

            var respCode = 0;
            var headers = new Dictionary<string, string>();
            var line = resultString.ReadLine();
            while (line != null)
            {
                if (line.StartsWith("HTTP/1.1 ") && line.Length > 11)
                    respCode = Convert.ToInt16(line.Substring(9, 3));
                else
                {
                    var items = line.Split(new[] { ':' }, 2);
                    if (items.Length == 2)
                        headers[items[0]] = items[1].TrimStart();
                }

                line = resultString.ReadLine();
            }

            if (respCode != (int) HttpStatusCode.SwitchingProtocols)
            {
                throw new WebSocketException($"The server returned status code '{respCode}' when status code '101' was expected");
            }

            if (!string.Equals(headers["Upgrade"], "WebSocket", StringComparison.OrdinalIgnoreCase)
                || !string.Equals(headers["Connection"], "Upgrade", StringComparison.OrdinalIgnoreCase)
                || !string.Equals(headers["Sec-WebSocket-Accept"], expectedAccept))
            {
                throw new WebSocketException("HTTP header error during handshake");
            }

            _state = WebSocketState.Open;

            if (_keepAliveInterval != Timeout.InfiniteTimeSpan)
            {
                _keepAliveTimer = new Timer(SendKeepAlive, this, _keepAliveInterval, _keepAliveInterval);
            }
        }
コード例 #21
0
        /// <summary>
        /// Обработка запроса: отправка на сервер, получение результата
        /// </summary>
        /// <param name="request"></param>
        /// <param name="networkStream"></param>
        /// <returns></returns>
        private static async Task<string> ProcessRequest(string request, NetworkStream networkStream)
        {
            // отсекаем пустые запросы к серверу. Запрос c null сознательно не отсекаем - флаг отключения клиента
            if (string.IsNullOrEmpty(request) && request != null)
            {
                return null;
            }

            byte[] requestBytes = Encoding.ASCII.GetBytes(request);

            await networkStream.WriteAsync(requestBytes, 0, requestBytes.Length);

            var buffer = new byte[8192];
            var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
            return Encoding.ASCII.GetString(buffer, 0, byteCount);
            
        }
コード例 #22
0
 internal static ValueTask WriteAsync(this NetworkStream stream, ReadOnlyMemory <byte> buffer)
 {
     return(stream.WriteAsync(buffer, default));
 }
 async Task SendAsync(NetworkStream stream, string data)
 {
     var buffer = Encoding.UTF8.GetBytes(data);
     await stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
 }
コード例 #24
0
ファイル: SocksTcpClient.cs プロジェクト: pendo324/Cobalt
	    private async Task WriteStringAsync(NetworkStream stream, string str)
	    {
	        if (str.Length > 255)
	        {
	            str = str.Substring(0, 255);
	        }
	        await stream.WriteByteAsync((byte) str.Length);
	        var buffer = Encoding.ASCII.GetBytes(str);
	        await stream.WriteAsync(buffer, 0, buffer.Length);
	    }
コード例 #25
0
        private async Task ProcessSentTasksAsync(NetworkStream netStream, SocketPayloadSendTask sendTask)
        {
            if (sendTask == null) return;

            using (sendTask)
            {
                var failed = false;
                var sw = Stopwatch.StartNew();
                try
                {
                    sw.Restart();
                    if (UseStatisticsTracker())
                    {
                        StatisticsTracker.IncrementGauge(StatisticGauge.ActiveWriteOperation);
                    }
                    if (OnWriteToSocketAttempt != null) OnWriteToSocketAttempt(sendTask.Payload);

                    _log.DebugFormat("Sending data for CorrelationId:{0} Connection:{1}", sendTask.Payload.CorrelationId, Endpoint);
                    await netStream.WriteAsync(sendTask.Payload.Buffer, 0, sendTask.Payload.Buffer.Length, _disposeToken.Token).ConfigureAwait(false);
                    _log.DebugFormat("Data sent to CorrelationId:{0} Connection:{1}", sendTask.Payload.CorrelationId, Endpoint);
                    sendTask.Tcp.TrySetResult(sendTask.Payload);
                }
                catch (Exception ex)
                {
                    failed = true;
                    var wrappedException = WrappedException(ex);
                    sendTask.Tcp.TrySetException(wrappedException);
                    throw;
                }
                finally
                {
                    if (UseStatisticsTracker())
                    {
                        StatisticsTracker.DecrementGauge(StatisticGauge.ActiveWriteOperation);
                        StatisticsTracker.CompleteNetworkWrite(sendTask.Payload, sw.ElapsedMilliseconds, failed);
                    }
                }
            }
        }
コード例 #26
0
 private async Task WriteMemoryStreamAsync(NetworkStream ns, MemoryStream ms, int offset, int length, CancellationToken cancellationToken = default(CancellationToken)) {
    await ns.WriteAsync(BitConverter.GetBytes(length), 0, sizeof(int), cancellationToken).ConfigureAwait(false);
    await ns.WriteAsync(ms.GetBuffer(), offset, length, cancellationToken).ConfigureAwait(false);
    outboundBytesAggregator.Put(sizeof(int) + length);
 }
コード例 #27
0
ファイル: RemoteSender.cs プロジェクト: cole2295/BitSharp
        public async Task SendMessageAsync(Message message)
        {
            try
            {
                await semaphore.DoAsync(async () =>
                {
                    using (var stream = new NetworkStream(socket))
                    {
                        var stopwatch = Stopwatch.StartNew();

                        using (var byteStream = new MemoryStream())
                        using (var writer = new BinaryWriter(byteStream))
                        {
                            NodeEncoder.EncodeMessage(writer, message);

                            var messageBytes = byteStream.ToArray();
                            await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
                        }

                        stopwatch.Stop();

                        if (logger.IsTraceEnabled)
                            logger.Trace($"Sent {message.Command} in {stopwatch.ElapsedMilliseconds} ms\nPayload: {message.Payload.ToArray().ToHexDataString()}");
                    }
                });
            }
            catch (Exception e)
            {
                Fail(e);
            }
        }
コード例 #28
0
        static async void forward(string prefix, NetworkStream from, NetworkStream to, Action close)
        {

            var buffer = new byte[1024 * 1024];

            do
            {
                // why no implict buffer?
                var count = await from.ReadAsync(buffer, 0, buffer.Length);

                Console.WriteLine(prefix + count);

                //                I/System.Console( 6199): > 393
                //I/System.Console( 6199): < 85
                //I/System.Console( 6199): < -1

                if (count < 0)
                {
                    close();
                    return;
                }

                await to.WriteAsync(buffer, 0, count);
            }
            while (true);
        }