[Quote=引用 17 楼 bbbbbb888888 的回复:]
引自msdn:
TcpClient:
public void Close ()
Close 方法可将该实例标记为已释放,但不关闭 TCP 连接。如果调用此方法,将不会释放用于发送和接收数据的 NetworkStream。您必须调用 Close 方法才能关闭该流和 TCP 连接。
--------------------------------------------------
NetworkStream:
public void Close()
Close 方法释放与 NetworkStream 关联的非托管资源和托管资源。如果 NetworkStream 拥有基础 Soc…
[/Quote]
Close()
释放此 TcpClient 实例,而不关闭基础连接。
备注
Close 方法将该实例标记为已释放并关闭 TCP 连接。调用此方法将关闭 Socket,并且还将关闭用于发送和接收数据的关联 NetworkStream(如果创建有一个这样的流)。
地址。。
http://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcpclient.close.aspx
Close 方法可将该实例标记为已释放,但不关闭 TCP 连接。如果调用此方法,将不会释放用于发送和接收数据的 NetworkStream。您必须调用 Close 方法才能关闭该流和 TCP 连接。
--------------------------------------------------
NetworkStream:
public void Close()
Close 方法释放与 NetworkStream 关联的非托管资源和托管资源。如果 NetworkStream 拥有基础 Socket,则后者也会关闭。
// 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();
用socket
TcpClient client = new TcpClient();
Socket s = client.Client;
if (!s.Connected)
{
s.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveBuffer, 16384);
Console.WriteLine(
"client is not connected, ReceiveBuffer set\n");
}
else
Console.WriteLine("client is connected");