当前位置: 首页>>代码示例>>C#>>正文


C# NetworkStream.WriteAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.NetworkStream.WriteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# NetworkStream.WriteAsync方法的具体用法?C# NetworkStream.WriteAsync怎么用?C# NetworkStream.WriteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.NetworkStream的用法示例。


在下文中一共展示了NetworkStream.WriteAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendMessageAsync

        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);
            }
        }
开发者ID:holinov,项目名称:BitSharp,代码行数:28,代码来源:RemoteSender.cs

示例2: AuthenticateV5

        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();
            }
        }
开发者ID:rburda82,项目名称:proxysearcher,代码行数:28,代码来源:SocksRequest.cs

示例3: ConvertStream

        /// <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;
        }
开发者ID:noricube,项目名称:IRCProxy,代码行数:36,代码来源:ProxyServer.cs

示例4: V5

        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();
            }
        }
开发者ID:rburda82,项目名称:proxysearcher,代码行数:30,代码来源:SocksRequest.cs

示例5: handleNetworkStream

 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);
     }
 }
开发者ID:hythof,项目名称:csharp_tcp_server_benchmark,代码行数:25,代码来源:AwaitServer.cs

示例6: AcceptingMessagesFromClient

        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();
            });
        }
开发者ID:gderham,项目名称:fixity,代码行数:58,代码来源:TcpServerActor.cs

示例7: WriteAsync

        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;
        }
开发者ID:roberino,项目名称:linqinfer,代码行数:16,代码来源:AsyncSocketWriterReader.cs

示例8: Sender

 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;
         }
     }
 }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:18,代码来源:Program.cs

示例9: SendMsg

    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);

    }
开发者ID:DVDPT,项目名称:Programmatically-Speaking-Repository,代码行数:18,代码来源:messages.cs

示例10: V4

        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();
            }
        }
开发者ID:rburda82,项目名称:proxysearcher,代码行数:21,代码来源:SocksRequest.cs

示例11: ConnectAsync

		/// <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);
		}
开发者ID:BananaScheriff,项目名称:legoev3,代码行数:43,代码来源:NetworkCommunication.cs

示例12: AcceptWebSocketAsync

		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);
		}
开发者ID:Rubenovich,项目名称:mono,代码行数:27,代码来源:HttpListenerContext.cs

示例13: CommunicateWithClientUsingNetworkStreamAsync

        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);
            }
        }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:32,代码来源:Program.cs

示例14: ClientSend

        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);
        }
开发者ID:quang319,项目名称:Penn-State-Fall,代码行数:16,代码来源:TcpTorrent.cs

示例15: writeMessageAsync

 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());
     }
 }
开发者ID:borjafdezgauna,项目名称:RLSimion,代码行数:21,代码来源:netTransfer.cs


注:本文中的System.Net.Sockets.NetworkStream.WriteAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。