TcpClient.Close 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
释放此 TcpClient 实例,并请求关闭基础 TCP 连接。
public:
void Close();
public void Close ();
member this.Close : unit -> unit
Public Sub Close ()
示例
下面的代码示例演示如何通过调用 Close
方法关闭 TcpClient 。
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::Sockets;
int main()
{
// Create a client that will connect to a
// server listening on the contoso1 computer
// at port 11000.
TcpClient^ tcpClient = gcnew TcpClient;
tcpClient->Connect( "contosoServer", 11000 );
// Get the stream used to read the message sent by the server.
NetworkStream^ networkStream = tcpClient->GetStream();
// Set a 10 millisecond timeout for reading.
networkStream->ReadTimeout = 10;
// Read the server message into a byte buffer.
array<Byte>^bytes = gcnew array<Byte>(1024);
networkStream->Read( bytes, 0, 1024 );
//Convert the server's message into a string and display it.
String^ data = Encoding::UTF8->GetString( bytes );
Console::WriteLine( "Server sent message: {0}", data );
networkStream->Close();
tcpClient->Close();
}
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Examples.System.Net
{
public class TCPClientExample
{
public static void Main()
{
// Create a client that will connect to a
// server listening on the contosoServer computer
// at port 11000.
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("contosoServer", 11000);
// Get the stream used to read the message sent by the server.
NetworkStream networkStream = tcpClient.GetStream();
// Set a 10 millisecond timeout for reading.
networkStream.ReadTimeout = 10;
// Read the server message into a byte buffer.
byte[] bytes = new byte[1024];
networkStream.Read(bytes, 0, 1024);
//Convert the server's message into a string and display it.
string data = Encoding.UTF8.GetString(bytes);
Console.WriteLine("Server sent message: {0}", data);
networkStream.Close();
tcpClient.Close();
}
}
}
注解
方法 Close
将实例标记为已释放,并请求关联的 Socket 关闭 TCP 连接。 根据 LingerState 属性,当仍要发送数据时,在调用 方法后, Close
TCP 连接可能会保持打开状态一段时间。 基础连接完成关闭后,不会提供通知。
调用此方法最终将导致关联的 Socket
关闭,并且还会关闭用于发送和接收数据的关联 NetworkStream (如果已创建)。
备注
当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。 有关详细信息,请参阅.NET Framework中的网络跟踪。