C# socket,Tcp和Udp


應用程序可以通過 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.Net.Sockets;
using System.Text;
using System.Net;


namespace Tcpclient
{
    public class TcpTimeClient
    {
        private static int portNum = 11000;
        private static string hostName = Dns.GetHostName().ToString();

        public static void Main(String[] args)
        {
            try
            {
                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());
            }

           
            Console.Read();
        }
    }
}

2.TcpListener
   TcpListener 類提供一些簡單方法,用於在阻止同步模式下偵聽和接受傳入連接請求。可使用 TcpClient 或 Socket 來連接 TcpListener。可使用 IPEndPoint、本地 IP 地址及端口號或者僅使用端口號,來創建 TcpListener。可以將本地 IP 地址指定為Any,將本地端口號指定為 0(如果希望基礎服務提供程序為您分配這些值)。如果您選擇這樣做,可在連接套接字后使用LocalEndpoint 屬性來標識已指定的信息。

 
         

    Start 方法用來開始偵聽傳入的連接請求。Start 將對傳入連接進行排隊,直至您調用 Stop 方法或它已經完成 MaxConnections 排隊為止。可使用 AcceptSocket 或 AcceptTcpClient 從傳入連接請求隊列提取連接。這兩種方法將阻止。如果要避免阻止,可首先使用 Pending 方法來確定隊列中是否有可用的連接請求。

 
         

    調用 Stop 方法來關閉 TcpListener。

 
         

    下面的例子給出怎么利用TcpListener監聽客戶端的請求:

using System;
using System.Net.Sockets;
using System.Text;

namespace Tcplistener
{
    public class TcpTimeServer
    {

        private const int portNum = 11000;

        public static int Main(String[] args)
        {
            bool done = false;

            TcpListener listener = new TcpListener(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();

            return 0;
        }

    }
}

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;

namespace Udpclient2
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient udpClient = new UdpClient(12000);
           
                try
                {
                    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                    string returnData = Encoding.ASCII.GetString(receiveBytes);
                    while (returnData != "")
                    {
                        udpClient.Connect(RemoteIpEndPoint.Address.ToString(), Convert.ToInt32(RemoteIpEndPoint.Port));
                        Byte[] sendBytes = Encoding.ASCII.GetBytes("I'm here.");

                        udpClient.Send(sendBytes, sendBytes.Length);

                        Console.WriteLine("This is the message you received " +
                                                     returnData.ToString());
                        Console.WriteLine("This message was sent from " +
                                                    RemoteIpEndPoint.Address.ToString() +
                                                    " on their port number " +
                                                    RemoteIpEndPoint.Port.ToString());

                        udpClient.Close();
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
           
            Console.Read();
        }
    }
}

連接端:

using System;
using System.Net.Sockets;
using System.Text;
using System.Net;

namespace Udpclient
{
    class Program
    {
        static void Main(string[] args)
        {
            // This constructor arbitrarily assigns the local port number.
            UdpClient udpClient = new UdpClient(11000);
            try
            {
                udpClient.Connect(Dns.GetHostName().ToString(), 12000);

                // Sends a message to the host to which you have connected.
                Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

                udpClient.Send(sendBytes, sendBytes.Length);

               

                //IPEndPoint object will allow us to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                string returnData = Encoding.ASCII.GetString(receiveBytes);

                // Uses the IPEndPoint object to determine which of these two hosts responded.
                Console.WriteLine("This is the message you received " +
                                             returnData.ToString());
                Console.WriteLine("This message was sent from " +
                                            RemoteIpEndPoint.Address.ToString() +
                                            " on their port number " +
                                            RemoteIpEndPoint.Port.ToString());

                udpClient.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Read();

        }
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM