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


C# TcpClient.GetStream方法代码示例

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


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

示例1: TcpClient

TcpClient tcpClient = new TcpClient ();

// Uses the GetStream public method to return the NetworkStream.
NetworkStream netStream = tcpClient.GetStream ();

if (netStream.CanWrite)
{
    Byte[] sendBytes = Encoding.UTF8.GetBytes ("Is anybody there?");
    netStream.Write (sendBytes, 0, sendBytes.Length);
}
else
{
    Console.WriteLine ("You cannot write data to this stream.");
    tcpClient.Close ();

    // Closing the tcpClient instance does not close the network stream.
    netStream.Close ();
    return;
}

if (netStream.CanRead)
{
    // Reads NetworkStream into a byte buffer.
    byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

    // Read can return anything from 0 to numBytesToRead. 
    // This method blocks until at least one byte is read.
    netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);

    // Returns the data received from the host to the console.
    string returndata = Encoding.UTF8.GetString (bytes);

    Console.WriteLine ("This is what the host returned to you: " + returndata);
}
else
{
    Console.WriteLine ("You cannot read data from this stream.");
    tcpClient.Close ();

    // Closing the tcpClient instance does not close the network stream.
    netStream.Close ();
    return;
}
netStream.Close();
开发者ID:.NET开发者,项目名称:System.Net.Sockets,代码行数:44,代码来源:TcpClient.GetStream

示例2: TcpClient.GetStream()

/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpListenerSample
{
   public static void Main()
   {
      int recv;
      byte[] data = new byte[1024];

      TcpListener newsock = new TcpListener(9050);
      newsock.Start();
      Console.WriteLine("Waiting for a client...");

      TcpClient client = newsock.AcceptTcpClient();
      NetworkStream ns = client.GetStream();

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);

      while(true)
      {
         data = new byte[1024];
         recv = ns.Read(data, 0, data.Length);
         if (recv == 0)
            break;
       
         Console.WriteLine(
                  Encoding.ASCII.GetString(data, 0, recv));
         ns.Write(data, 0, recv);
      }
      ns.Close();
      client.Close();
      newsock.Stop();
   }
}
开发者ID:C#程序员,项目名称:System.Net.Sockets,代码行数:47,代码来源:TcpClient.GetStream


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