本文整理汇总了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();
示例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();
}
}