ReadAsync() public method

public ReadAsync ( byte buffer, int offset, int size, CancellationToken cancellationToken ) : Task
buffer byte
offset int
size int
cancellationToken System.Threading.CancellationToken
return Task
示例#1
16
        private async Task<String> ReadRequest(NetworkStream stream)
        {
            var encoding = Encoding.UTF8;
            var i = 0;
            var bytes = new byte[1024];
            var sb = new StringBuilder();

            while ((i = await stream.ReadAsync(bytes, 0, bytes.Length)) != 0)
            {
                sb.Append(encoding.GetString(bytes, 0, i));

                if (!stream.DataAvailable) break;
            }

            return sb.ToString();
        }
示例#2
0
        public async Task<PingPayload> Ping(){

            NetworkStream = null;
            WriteBuffer.Clear();
            ReadOffset = 0;
            var client = new TcpClient();

            await client.ConnectAsync(Host, Port);
            if (!client.Connected)
                return null;
            
            NetworkStream = client.GetStream();


            /*
             * Send a "Handshake" packet
             * http://wiki.vg/Server_List_Ping#Ping_Process
             */
            WriteVarInt(47);
            WriteString(Host);
            WriteShort(Port);
            WriteVarInt(1);
            await Flush(0);

            /*
             * Send a "Status Request" packet
             * http://wiki.vg/Server_List_Ping#Ping_Process
             */
            await Flush(0);



            var message = new List<byte>();
            var buf = new byte[1024];
            var bytes = await NetworkStream.ReadAsync(buf, 0, buf.Length, CancellationToken);
            message.AddRange(new ArraySegment<byte>(buf, 0, bytes));
            var length = ReadVarInt(buf);
            var left = length - (message.Count - ReadOffset);
            while (left > 0) {
                buf = new byte[1024]; 
                bytes = await NetworkStream.ReadAsync(buf, 0, buf.Length, CancellationToken);
                message.AddRange(new ArraySegment<byte>(buf, 0, bytes));
                left -= bytes;
            }

            client.Close();

            ReadOffset = 0;
            var buffer = message.ToArray();
            length = ReadVarInt(buffer);
            ReadVarInt(buffer); // packetID
            var jsonLength = ReadVarInt(buffer);
            var json = ReadString(buffer, jsonLength);
            var ping = JsonConvert.DeserializeObject<PingPayload>(json);
            ping.Motd = ping.Motd != null ? CleanMotd(ping.Motd) : null;

            return ping;
        }
示例#3
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();
            }
        }
示例#4
0
        public async Task <byte[]> Receive()
        {
            if (!disposed)
            {
                // Reusable SocketAsyncEventArgs and awaitable wrapper



                try
                {
                    var bytes = await m_Socket.ReadAsync(internalBuffer, 0, internalBuffer.Length);

                    if (bytes > 0)
                    {
                        byte[] queueBuffer = new byte[bytes];
                        Array.Copy(internalBuffer, queueBuffer, bytes);
                        return(queueBuffer);
                    }
                }
                catch (Exception)
                {
                    disposed = true;
                }
            }
            return(null);
        }
示例#5
0
        /// <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;
        }
示例#6
0
 private async void ReadAsync(NetworkStream stream)
 {
     byte[] buffer = new byte[100];
     while (true)
     {
         try
         {
             int length = await stream.ReadAsync(buffer, 0, buffer.Length);
             Invoke(new MethodInvoker(delegate
             {
                 outputText.Append(buffer, length);
             }));
         }
         catch
         {
             if (this.Visible)
             { // we're not being closed
                 Invoke(new MethodInvoker(delegate
                 {
                     Stop();
                 }));
             }
             break;
         }
     }
 }
示例#7
0
        private async void buttonConnect_Click(object sender, RibbonControlEventArgs e)
        {
            if (!string.IsNullOrEmpty(comboBoxIp.Text))
            {
                try {

                    if (listner != null)
                    {
                        listner.Stop();
                        listner = null;
                    }
                    listner = new TcpListener(IPAddress.Parse(comboBoxIp.Text),port);
                    listner.Start();
                    labelStatus.Label = "データ待機中";
                    client = await listner.AcceptTcpClientAsync();
                    stream = client.GetStream();
                    byte[] buff = new byte[1];
                    var read = await stream.ReadAsync(buff, 0, buff.Length);
                    ExecuteCommand(buff[0]);
                    
                    
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("IPを選択してください");
            }

        }
        // read memory buffer helper
	async static Task<byte[]>ReadMessage(NetworkStream s)
	{
		MemoryStream ms = new System.IO.MemoryStream();
		byte[] buffer = new byte[0x1000];
		do { ms.Write(buffer, 0, await s.ReadAsync(buffer, 0, buffer.Length)); }
		while (s.DataAvailable);
		return ms.ToArray();
	}
 // Receive a message synchronously
 public static async Task<object> RecvMsg(NetworkStream stream)
 {
     byte[] lenbuf = new byte[MSG_HDR_SIZE];
     // receive message length
     int bytesRead = await stream.ReadAsync(lenbuf, 0, lenbuf.Length);
     if (bytesRead != MSG_HDR_SIZE)
         throw new ApplicationException(String.Format("RecvMessage: unexpected message length size with {0} bytes", bytesRead));
     // receive message payload
     return await RecvMsg(stream, lenbuf);
 }
		/// <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);
		}
示例#11
0
        public static void Run()
        {
            var socket = SocketBuilder.GetSocket();
            var networkStream = new NetworkStream(socket);
            var buffer = new byte[0x1000];

            // begin
            var task = networkStream.ReadAsync(buffer, 0, 1);
            // end

            task.Wait();

            Logger.Log("Byte: {0}", buffer[0]);
        }
 // Receive message payload synchronously, after length has been received
 private static async Task<object> RecvMsg(NetworkStream stream, byte[] lenbuf)
 {
     // compute message length
     int memlen = BitConverter.ToInt32(lenbuf, 0) - MSG_HDR_SIZE;
     // allocate a byte array for the remainder of message
     byte[] membuf = new byte[memlen];
     // receive the remainder of message
     int bytesRead = 0;
     while (bytesRead < memlen)
     {
         bytesRead += await stream.ReadAsync(membuf, bytesRead, memlen - bytesRead);
     }
     // create a stream from message content and get the object graph
     MemoryStream memstm = new MemoryStream(membuf);
     BinaryFormatter fmtr = new BinaryFormatter();
     return fmtr.Deserialize(memstm);
 }
示例#13
0
 protected async Task<byte[]> ReceiveAsync(NetworkStream stream)
 {
     try
     {
         int len = await stream.ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length);
         stream.Flush();
         // 异步接收回答
         if (len > 0)
         {
             return CheckReplyDatagram(len);
         }
         return null;
     }
     catch (Exception err)
     {
         AddInfo("receive exception: " + err.Message);
         CloseClientSocket();
         return null;
     }
 }
示例#14
0
	    private async Task<int> ReadAsync(NetworkStream stream, byte[] buffer, int count)
	    {
	        var timeout = Task.Delay(SocksTimeout);
	        var readTask = stream.ReadAsync(buffer, 0, count);
	        var completed = await Task.WhenAny(timeout, readTask).ConfigureAwait(false);
	        if (completed == readTask)
	        {
	            int read = await readTask; // so we can throw exceptions
	            if (read < 2)
	            {
	                throw new SocksException("Unable to negotiate with the proxy.");
	            }
	            else
	            {
	                return read;
	            }
	        }
	        else
	        {
	            throw new SocksException("The proxy did not respond in a timely manner.");
	        }
	    }
示例#15
0
 //public void readFromNetworkStream(TcpClient client, NetworkStream stream)
 //{
 //    discardProcessedData();
 //    //read if there's something to read and if we have available storage
 //    do
 //    {
 //        //CJobDispatcher.checkConnection(client);
 //        if (stream.DataAvailable && m_bytesInBuffer < m_maxChunkSize)
 //        {
 //            m_bytesInBuffer += stream.Read(m_buffer, m_bytesInBuffer, m_maxChunkSize - m_bytesInBuffer);
 //        }
 //        if (m_bytesInBuffer == 0) Thread.Sleep(200);
 //    } while (m_bytesInBuffer == 0);
 //}
 public async Task<int> readFromNetworkStreamAsync(TcpClient client, NetworkStream stream,CancellationToken cancelToken)
 {
     int numBytesRead= 0;
     discardProcessedData();
     //read if there's something to read and if we have available storage
     try { numBytesRead = await stream.ReadAsync(m_buffer, m_bytesInBuffer, m_maxChunkSize - m_bytesInBuffer, cancelToken); }
     catch (OperationCanceledException) { logMessage("async read from network stream cancelled"); }
     m_bytesInBuffer += numBytesRead;
     return numBytesRead;
 }
示例#16
0
        public async Task<ServerClientMsg> ClientReceive(NetworkStream networkStream)
        {
            var ReadBytes = new byte[8192];
            ServerClientMsg ReceivedObject = new ServerClientMsg();

            int BytesRead = await networkStream.ReadAsync(ReadBytes, 0, ReadBytes.Length);
            if (BytesRead > 0)
            {
                ClientSb.Append(Encoding.UTF8.GetString(ReadBytes, 0, BytesRead));
                var ReceivedMsg = ClientSb.ToString();
                if (ReceivedMsg.IndexOf("</TcpMsg>") > -1)
                {
                    XmlSerializer xmlS = new XmlSerializer(typeof(ServerClientMsg));
                    using (var stringReader = new StringReader(ReceivedMsg))
                    {
                        ReceivedObject = (ServerClientMsg)xmlS.Deserialize(stringReader);
                    }
                    ClientSb.Clear();
                }
            }
            return ReceivedObject;
            
        }
示例#17
0
        public static async Task<Packet> ReadFromStreamAsync(NetworkStream stream)
        {
            Packet packet = new Packet();

            byte[] sizeBuffer = new byte[4];
            stream.Read(sizeBuffer, 0, 4);
            packet.PacketSize = BitConverter.ToInt32(sizeBuffer, 0);

            byte[] packetBuffer = new byte[packet.PacketSize];
            if(packet.PacketSize != 0)
            {
                int readProgress = 0;
                while(readProgress < packet.PacketSize)
                {
                    int read = await stream.ReadAsync(packetBuffer, readProgress, packet.PacketSize - readProgress);
                    readProgress += read;

                    if(read == 0)
                    {
                        throw new Exception("NetworkStream failed to read data.  Connection may have been lost!");
                    }
                }
            }

            packet.Opcode = (Opcode)BitConverter.ToInt32(packetBuffer, 0);
            packet.Type = (PacketType)BitConverter.ToInt32(packetBuffer, 4);
            Array.Copy(packetBuffer, 8, packet.Data, 0, packet.DataSize);

            Console.WriteLine("Recieved {0}", packet.DataAsString());
            return packet;
        }
        public static async Task Receiver(NetworkStream stream, CancellationToken token)
        {
            try
            {
                stream.ReadTimeout = 5000;
                WriteLine("Receiver task");
                byte[] readBuffer = new byte[ReadBufferSize];
                while (true)
                {
                    Array.Clear(readBuffer, 0, ReadBufferSize);

                    int read = await stream.ReadAsync(readBuffer, 0, ReadBufferSize, token);
                    string receivedLine = Encoding.UTF8.GetString(readBuffer, 0, read);
                    WriteLine($"received {receivedLine}");
                }
            }
            catch (OperationCanceledException ex)
            {
                WriteLine(ex.Message);
            }
        }
示例#19
0
        /// <summary>
        /// Reads from the stream with provided timeout
        /// </summary>
        /// <param name="stream">The stream to read from</param>
        /// <param name="buffer">The byte buffer</param>
        /// <param name="offset">The stream offset</param>
        /// <param name="length">The number of bytes to read</param>
        /// <param name="timeout">The timeout</param>
        /// <returns>The number of read bytes</returns>
        private async Task<int> ReadWithTimeout(
            NetworkStream stream,
            byte[] buffer,
            int offset,
            int length,
            TimeSpan timeout)
        {
            var tokenSource = new CancellationTokenSource();
            var ct = tokenSource.Token;

            var task = stream.ReadAsync(buffer, offset, length, ct); 
            if (await Task.WhenAny(task, Task.Delay(timeout, ct)) == task)
            {
                tokenSource.Cancel();
                return task.Result;
            }

            tokenSource.Cancel();
            throw new ParcelTimeoutException { Notification = this };
        }
        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);
            }
        }
        async Task<bool> fill(NetworkStream stream, byte[] buffer, int rest)
        {
            if (rest > buffer.Length)
            {
                return false;
            }

            int offset = 0;
            while (rest > 0)
            {
                var length = await stream.ReadAsync(buffer, offset, rest).ConfigureAwait(false);
                Interlocked.Increment(ref ReadCount);
                if (length == 0)
                {
                    return false;
                }
                rest -= length;
                offset += length;
            }
            return true;
        }
示例#22
0
        private async Task ProcessReadTaskAsync(NetworkStream netStream, SocketPayloadReadTask readTask)
        {
            using (readTask)
            {
                try
                {
                    if (UseStatisticsTracker())
                    {
                        StatisticsTracker.IncrementGauge(StatisticGauge.ActiveReadOperation);
                    }
                    var readSize = readTask.ReadSize;
                    var result = new List<byte>(readSize);
                    var bytesReceived = 0;

                    while (bytesReceived < readSize)
                    {
                        readSize = readSize - bytesReceived;
                        var buffer = new byte[readSize];

                        if (OnReadFromSocketAttempt != null) OnReadFromSocketAttempt(readSize);

                        bytesReceived = await netStream.ReadAsync(buffer, 0, readSize, readTask.CancellationToken).ConfigureAwait(false);

                        if (OnBytesReceived != null) OnBytesReceived(bytesReceived);

                        if (bytesReceived <= 0)
                        {
                            using (_client)
                            {
                                _client = null;
                                if (_disposeToken.IsCancellationRequested) { return; }

                                throw new BrokerConnectionException(string.Format("Lost connection to server: {0}", _endpoint), _endpoint);
                            }
                        }

                        result.AddRange(buffer.Take(bytesReceived));
                    }

                    readTask.Tcp.TrySetResult(result.ToArray());
                }
                catch (Exception ex)
                {
                    if (_disposeToken.IsCancellationRequested)
                    {
                        var exception = new ObjectDisposedException(string.Format("Object is disposing (KafkaTcpSocket for endpoint: {0})", Endpoint));
                        readTask.Tcp.TrySetException(exception);
                        throw exception;
                    }

                    if (ex is BrokerConnectionException)
                    {
                        readTask.Tcp.TrySetException(ex);
                        if (_disposeToken.IsCancellationRequested) return;
                        throw;
                    }

                    //if an exception made us lose a connection throw disconnected exception
                    if (_client == null || _client.Connected == false)
                    {
                        var exception = new BrokerConnectionException(string.Format("Lost connection to server: {0}", _endpoint), _endpoint);
                        readTask.Tcp.TrySetException(exception);
                        throw exception;
                    }

                    readTask.Tcp.TrySetException(ex);
                    if (_disposeToken.IsCancellationRequested) return;

                    throw;
                }
                finally
                {
                    if (UseStatisticsTracker())
                    {
                        StatisticsTracker.DecrementGauge(StatisticGauge.ActiveReadOperation);
                    }
                }
            }
        }
示例#23
0
        public async Task<byte[]> GetRawRequestAsync(NetworkStream stream)
        {
            Requires.NotNull(stream, "stream");

            if (!stream.CanRead)
            {
                throw new IOException();
            }

            var buffer = new byte[DefaultBufferSize];
            using (var memoryStream = new MemoryStream(DefaultBufferSize))
            {
                while (stream.DataAvailable)
                {
                    int read = await stream.ReadAsync(buffer, 0, buffer.Length);
                    // resize a raw request array
                    await memoryStream.WriteAsync(buffer, 0, read);
                }
                return memoryStream.ToArray();
            }
        }
示例#24
0
        /// <summary>
        /// Extend the buffer size by BufferSegment class each time, that avoid the copy of buffer.
        /// In buffer will grow when it is remaining buffer is less than 512 bytes.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static async Task ProcessLineWithAdvancedGrowthBufferAndBufferRecycleAsync(this NetworkStream stream)
        {
            const int minimumBufferSize = 512;

            var segments = new List <BufferSegment>();
            // The index of consumed bytes in the first segment
            var bytesConsumed = 0;
            // The bytes that buffered in current segment
            var bytesBuffered = 0;
            var segment       = new BufferSegment {
                Buffer = ArrayPool <byte> .Shared.Rent(1024)
            };

            segments.Add(segment);

            while (true)
            {
                if (segment.Remaining < minimumBufferSize)
                {
                    // Remove the current segment if it has not any valid data
                    if (segment.Count == bytesConsumed)
                    {
                        segments.RemoveAt(0);
                        bytesConsumed = 0;
                    }
                    // Allocate a new segment
                    segment = new BufferSegment {
                        Buffer = ArrayPool <byte> .Shared.Rent(1024)
                    };
                    segments.Add(segment);
                    bytesBuffered = 0;
                }
                var bytesRead = 0;
                try
                {
                    bytesRead = await stream.ReadAsync(segment.Buffer, segment.Count, segment.Remaining);
                }
                catch (IOException e)
                {
                    Console.WriteLine($"{e.Message}");
                    return;
                }
                if (bytesRead == 0)
                {
                    break;
                }
                segment.Count += bytesRead;
                bytesBuffered += bytesRead;

                // Process multiple line
                while (true)
                {
                    // Look for line end delimiter
                    var startIndex   = segments.Count == 1 ? bytesConsumed : 0;
                    var count        = segments.Count == 1 ? segment.Count - bytesConsumed : segment.Count;
                    var linePosition = Array.IndexOf(segment.Buffer, (byte)'\n', startIndex, count);
                    if (linePosition >= 0)
                    {
                        ProcessLine(segments, linePosition, bytesConsumed);

                        bytesConsumed = linePosition + 1;

                        // Drop fully consumed segments from the list so we don't look at them again
                        for (int i = segments.Count - 1; i >= 0; --i)
                        {
                            var consumedSegment = segments[i];

                            // Return all segment unless the last segment
                            if (consumedSegment != segment)
                            {
                                ArrayPool <byte> .Shared.Return(consumedSegment.Buffer);

                                segments.RemoveAt(i);
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
示例#25
0
        public async Task<int> CalculatePrefix(NetworkStream netStream)
        {
            var packetSize = new List<byte>(sizeof(int));
            var tmpBuff = new byte[1];

            while (true)
            {
                // receive 1 byte at a time, ensuring complete packet
                var read = await netStream.ReadAsync(tmpBuff, 0, 1);

                if (read == 0)
                    return -1;

                packetSize.AddRange(tmpBuff);

                // if entire integer has been read then return calculated packet size
                if (packetSize.Count >= sizeof(int))
                    return BitConverter.ToInt32(packetSize.ToArray(), 0);
            }
        }
示例#26
0
		private async Task<bool> TryReadAsync(TcpClient client, NetworkStream stream, byte[] buffer, int length, CancellationToken token)
		{
			int readBytes = 0;

			while (readBytes < length)
			{
				if (token.IsCancellationRequested || !client.IsConnected())
					return false;

				readBytes += await stream.ReadAsync(buffer, readBytes, length - readBytes, token);
			}

			return true;
		}
示例#27
0
 private async Task StartServerAsync()
 {
     try {
         
         listner = new TcpListener(IPAddress.Parse("127.0.0.1"), int.Parse(SettingManager.ServerPort));
         listner.Start();
         LogList.Add("ServerListen 127.0.0.1 Port=" + SettingManager.ServerPort);
         client = await listner.AcceptTcpClientAsync();
         LogList.Add("Client Accepted");
         stream = client.GetStream();
         while (true)
         {
             if (client.Available > 0) {
                 byte[] buff = new byte[client.Available];
                 var read = await stream.ReadAsync(buff, 0, buff.Length);
                 var json = Encoding.UTF8.GetString(buff);
                 var data = JsonConvert.DeserializeObject<ConnectionData>(json);
                 if (data.AcceptPass == Setting.PassCode)
                 {
                     LogList.Add("Script Run ["+data.Script+"]");
                     Process.Start(Setting.PowerShellPath,data.Script);
                 }
                 else
                 {
                     MessageBox.Show("パスコードが違うようです。CortanaCommandアプリの設定からパスコードを取得し、サーバーの設定にペーストしてください");
                 }
                 client.Close();
                 listner.Stop();
                 await StartServerAsync();
                 break;
             }
             else
             {
                 await Task.Delay(100);
             }
         }
     }
     catch (Exception e)
     {
         LogList.Add(e.Message);
         client.Close();
         listner.Stop();
         await StartServerAsync();
     }
 }
示例#28
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);
            
        }
        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);
            }
        }
示例#30
0
        private async Task<byte[]> ReadBytes(NetworkStream stream, int count, CancellationToken cancellationToken)
        {
            if (count <= 0)
                throw new ArgumentException();
            byte[] buffer = new byte[count];
            int received = 0;
            while (received != count)
            {
                int result = await stream.ReadAsync(buffer, received, count - received, cancellationToken);

                if (result == 0)
                {
                    throw new SocketException(10060);
                }

                received += result;
            }

            return buffer;
        }
        public async Task<TcpReceiveContext> ReadAsync()
        {
            using (var cancellationTokenSource = new CancellationTokenSource(Timeout))
            {
                var socketStream = new NetworkStream(_socket);
                var receivedStream = new MemoryStream();
                var read = 0;

                TcpRequestHeader header = null;

                while (true)
                {
                    read = await socketStream.ReadAsync(_readBuffer, 0, _readBuffer.Length, cancellationTokenSource.Token);

                    if (header == null)
                    {
                        header = new TcpRequestHeader(_readBuffer);
                    }
                    else
                    {
                        header.Append(_readBuffer);
                    }

                    if (header.IsComplete || read < _readBuffer.Length) break;
                }

                if ((read - header.HeaderLength) > 0)
                    receivedStream.Write(_readBuffer, header.HeaderLength, read - header.HeaderLength);

                while (receivedStream.Position < header.ContentLength)
                {
                    read = await socketStream.ReadAsync(_readBuffer, 0, _readBuffer.Length, cancellationTokenSource.Token);

                    receivedStream.Write(_readBuffer, 0, read);
                }

                DebugOutput.Log("Received {0} bytes", receivedStream.Position);

                receivedStream.Position = 0;

                return new TcpReceiveContext(_socket)
                {
                    Header = header,
                    ReceivedData = receivedStream
                };
            }
        }
 /*
  * These overloads are in the API reference, but our System.dll internals are visible
  * to the tests.  This causes the compiler to incorrectly resolve these against the
  * overloaded version.
  *
  * The API reference has this in corlib:
  *
  *    ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
  *    ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
  *
  * In System.dll, we override this as
  *
  *    public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken)
  *
  * Without System.dll internals being visible, the compiler would correctly resolve the call using the
  * API reference, but we need this custom extension for the tests.
  */
 internal static ValueTask <int> ReadAsync(this NetworkStream stream, Memory <byte> buffer)
 {
     return(stream.ReadAsync(buffer, default));
 }
示例#33
0
 private async Task<IOutputStream> CreateMatchedHandler(
     IPEndPoint remote_endpoint,
     NetworkStream stream,
     AccessControlInfo acinfo)
 {
   var output_factories = PeerCast.OutputStreamFactories.OrderBy(factory => factory.Priority);
   var header = new byte[4096];
   int offset = 0;
   using (var cancel_source=new CancellationTokenSource(TimeSpan.FromMilliseconds(3000))) {
     var cancel_token = cancel_source.Token;
     cancel_token.Register(() => stream.Close());
     try {
       while (offset<header.Length) {
         var len = await stream.ReadAsync(header, offset, header.Length-offset);
         if (len==0) break;
         offset += len;
         var header_ary = header.Take(offset).ToArray();
         foreach (var factory in output_factories) {
           if ((acinfo.Accepts & factory.OutputStreamType) == 0) continue;
           var channel_id = factory.ParseChannelID(header_ary);
           if (channel_id.HasValue) {
             return factory.Create(
               stream,
               stream,
               remote_endpoint,
               acinfo,
               channel_id.Value,
               header_ary);
           }
         }
       }
     }
     catch (System.ObjectDisposedException) {
     }
     catch (System.IO.IOException) {
     }
   }
   return null;
 }