應用程序可以通過 TCPClient、TCPListener 和 UDPClient 類使用傳輸控制協議 (TCP) 和用戶數據文報協議 (UDP) 服務。這些協議類建立在 System.Net.Sockets.Socket 類的基礎之上,負責數據傳送的細節。(也就是說TCPClient、TCPListener 和 UDPClient 類是用來簡化Socket)
TcpClient 和 TcpListener 使用 NetworkStream 類表示網絡。使用 GetStream 方法返回網絡流,然后調用該流的 Read 和 Write 方法。NetworkStream 不擁有協議類的基礎套接字,因此關閉它並不影響套接字。
UdpClient 類使用字節數組保存 UDP 數據文報。使用 Send 方法向網絡發送數據,使用 Receive 方法接收傳入的數據文報。
1.TcpClient TcpClient 類提供了一些簡單的方法,用於在同步阻止模式下通過網絡來連接、發送和接收流數據。為使 TcpClient 連接並交換數據,使用 TCP ProtocolType 創建的 TcpListener 或 Socket 必須偵聽是否有傳入的連接請求。可以使用下面兩種方法之一連接到該偵聽器: (1)創建一個 TcpClient,並調用三個可用的 Connect 方法之一。 (2)使用遠程主機的主機名和端口號創建 TcpClient。此構造函數將自動嘗試一個連接。 給繼承者的說明要發送和接收數據,請使用 GetStream 方法來獲取一個 NetworkStream。調用 NetworkStream 的 Write 和 Read 方法與遠程主機之間發送和接收數據。使用 Close 方法釋放與 TcpClient 關聯的所有資源。
下面的例子給出怎么利用TcpClient連接到服務器:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace tcpclient
{
class Program
{
private static int portNum = 11000;
private static string hostName = Dns.GetHostName().ToString();
public static void Main(String[] args)
{
try
{
Console.WriteLine("主機名字:"+ Dns.GetHostName());
Console.WriteLine("主機IP地址:"+ Dns.GetHostAddresses(Dns.GetHostName())[0]);
TcpClient client = new TcpClient(hostName, portNum);
NetworkStream ns = client.GetStream();
byte[] bytes = new byte[1024];
int bytesRead = ns.Read(bytes, 0, bytes.Length);
//將字節流解碼為字符串
Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead));
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
2.TcpListener TcpListener 類提供一些簡單方法,用於在阻止同步模式下偵聽和接受傳入連接請求。可使用 TcpClient 或 Socket 來連接 TcpListener。可使用 IPEndPoint、本地 IP 地址及端口號或者僅使用端口號,來創建 TcpListener。可以將本地 IP 地址指定為 Any,將本地端口號指定為 0(如果希望基礎服務提供程序為您分配這些值)。如果您選擇這樣做,可在連接套接字后使用 LocalEndpoint 屬性來標識已指定的信息。
Start 方法用來開始偵聽傳入的連接請求。Start 將對傳入連接進行排隊,直至您調用 Stop 方法或它已經完成 MaxConnections 排隊為止。可使用 AcceptSocket 或 AcceptTcpClient 從傳入連接請求隊列提取連接。這兩種方法將阻止。如果要避免阻止,可首先使用 Pending (注:TcpListener類才有)方法來確定隊列中是否有可用的連接請求。
調用 Stop 方法來關閉 TcpListener。
下面的例子給出怎么利用TcpListener監聽客戶端的請求: using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace tcpclient
{
class Program
{
private const int portNum = 11000;
static void Main(string[] args)
{
bool done = false;
//TcpListener listener = new TcpListener(portNum); //根據VS2005 MSDN 此方法已經過時,不再使用
// IPEndPoint類將網絡標識為IP地址和端口號
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum));
listener.Start();
while (!done)
{
Console.Write("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
NetworkStream ns = client.GetStream();
byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
try
{
ns.Write(byteTime, 0, byteTime.Length);
ns.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
listener.Stop();
}
}
}
3.UdpClient UdpClient 類提供了一些簡單的方法,用於在阻止同步模式下發送和接收無連接 UDP 數據報。因為 UDP 是無連接傳輸協議,所以不需要在發送和接收數據前建立遠程主機連接。但您可以選擇使用下面兩種方法之一來建立默認遠程主機:
· 使用遠程主機名和端口號作為參數創建 UdpClient 類的實例。
· 創建 UdpClient 類的實例,然后調用 Connect 方法。
可以使用在 UdpClient 中提供的任何一種發送方法將數據發送到遠程設備。使用 Receive 方法可以從遠程主機接收數據。 UdpClient 方法還允許發送和接收多路廣播數據報。使用 JoinMulticastGroup 方法可以將 UdpClient 預訂給多路廣播組。使用 DropMulticastGroup 方法可以從多路廣播組中取消對 UdpClient 的預訂。
下面的例子演示同一主機不同端口之間的UDP通信:
監聽端: using System;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Threading;
namespace Udpclient2
{
class Program
{
static void Main(string[] args)
{
try
{
UdpClient udpClient = new UdpClient(12000);
string returnData = "client_end";
do
{
Console.WriteLine("服務器端接收數據:.............................");
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// 此處通過引用傳值,獲得客戶端的IP地址及端口號
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
//此處獲得客戶端的數據
returnData = Encoding.UTF8.GetString(receiveBytes);
//Encoding.ASCII.GetString(receiveBytes); 此處若用ASCII,不能正確處理中文
Console.WriteLine("This is the message server received: " + returnData.ToString());
Thread.Sleep(3000);
Console.WriteLine("向客戶端發送數據:.............................");
udpClient.Connect(Dns.GetHostName().ToString(), 11000);
// Sends a message to the host to which you have connected.
string sendStr = "我來自服務器端:" + DateTime.Now.ToString();
Byte[] sendBytes = Encoding.UTF8.GetBytes(sendStr);
//Byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr); 此處若用ASCII,不能正確處理中文
udpClient.Send(sendBytes, sendBytes.Length);
Console.WriteLine("This is the message server send: " + sendStr);
} while (returnData != "client_end");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
客戶端: using System;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace Udpclient
{
class Program
{
static void Main(string[] args)
{
try
{
UdpClient udpClient = new UdpClient(11000);
//向服務器發送數據
udpClient.Connect(Dns.GetHostName().ToString(), 12000);
// Sends a message to the host to which you have connected.
string sendStr = "我來自客戶端:" + DateTime.Now.ToString();
Byte[] sendBytes = Encoding.UTF8.GetBytes(sendStr);
//Byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr); 此處若用ASCII,不能正確處理中文
udpClient.Send(sendBytes, sendBytes.Length);
Console.WriteLine("This is the message client send: " + sendStr);
//等待服務器的答復,收到后顯示答復,並結束對話
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// 此處通過引用傳值,獲得客戶端的IP地址及端口號
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
//此處獲得服務器端的數據
string returnData = Encoding.UTF8.GetString(receiveBytes);
//Encoding.ASCII.GetString(receiveBytes); 此處若用ASCII,不能正確處理中文
Console.WriteLine("This is the message come from server: " + returnData.ToString());
udpClient.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}