GetStream 方法

cpClient.GetStream 方法
返回用于发送和接收数据的  NetworkStream

GetStream 返回一个可用来发送和接收数据的 NetworkStreamNetworkStream 类从 Stream 类继承,后者提供了大量为网络通信提供便利的方法和属性。

必须首先调用 Connect 方法,否则 GetStream 方法将引发 InvalidOperationException。获取NetworkStream 后,请调用 Write 方法将数据发送到远程主机。应调用 Read 方法来接收从远程主机传来的数据。这两种方法都将阻塞,直到执行了指定的操作为止。通过检查 DataAvailable 属性可避免对读取操作的阻止。true 值表示数据已从远程主机到达,可以进行读取。这样便保证立即完成 Read。如果远程主机已关闭连接,Read 将立即返回零字节。

 

注意:

在从发送数据到接收数据的整个过程中,必须关闭 NetworkStream。关闭 TcpClient 并不会释放 NetworkStream

例子:

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

}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值