Uso dei servizi TCPUsing TCP Services

La classe TcpClient richiede i dati da una risorsa Internet tramite TCP.The TcpClient class requests data from an Internet resource using TCP. I metodi e le proprietà di TcpClient ottengono un'astrazione dei dettagli per creare un Socket per la richiesta e la ricezione di dati tramite TCP.The methods and properties of TcpClient abstract the details for creating a Socket for requesting and receiving data using TCP. Dato che la connessione al dispositivo remoto è rappresentata come flusso, i dati possono essere letti e scritti con le tecniche di gestione dei flussi di .NET Framework.Because the connection to the remote device is represented as a stream, data can be read and written with .NET Framework stream-handling techniques.

Il protocollo TCP stabilisce una connessione con un endpoint remoto e quindi usa tale connessione per inviare e ricevere pacchetti di dati.The TCP protocol establishes a connection with a remote endpoint and then uses that connection to send and receive data packets. TCP è responsabile di garantire che i pacchetti di dati vengano inviati all'endpoint e assemblati nell'ordine corretto all'arrivo.TCP is responsible for ensuring that data packets are sent to the endpoint and assembled in the correct order when they arrive.

Per stabilire una connessione TCP, è necessario conoscere l'indirizzo del dispositivo di rete che ospita il servizio necessario ed è necessario conoscere la porta TCP usata dal servizio per comunicare.To establish a TCP connection, you must know the address of the network device hosting the service you need and you must know the TCP port that the service uses to communicate. IANA (Internet Assigned Numbers Authority) definisce i numeri di porta per i servizi comuni (vedere www.iana.org/assignments/port-numbers).The Internet Assigned Numbers Authority (Iana) defines port numbers for common services (see www.iana.org/assignments/port-numbers). I servizi non presenti nell'elenco IANA possono avere numeri di porta nell'intervallo da 1.024 a 65.535.Services not on the Iana list can have port numbers in the range 1,024 to 65,535.

L'esempio seguente illustra la configurazione di un TcpClient per connettersi a un server di riferimento ora sulla porta TCP 13.The following example demonstrates setting up a TcpClient to connect to a time server on TCP port 13.

Imports System  
Imports System.Net.Sockets  
Imports System.Text  

Public Class TcpTimeClient  
    Private const portNum As Integer = 13  
    Private const hostName As String = "host.contoso.com"  

    ' Entry point  that delegates to C-style main Private Function.  
    Public Overloads Shared Sub Main()  
        System.Environment.ExitCode = _  
            Main(System.Environment.GetCommandLineArgs())  
    End Sub  

    Overloads Public Shared Function Main(args() As [String]) As Integer  
        Try  
            Dim client As New TcpClient(hostName, portNum)  

            Dim ns As NetworkStream = client.GetStream()  

            Dim bytes(1024) As Byte  
            Dim bytesRead As Integer = ns.Read(bytes, 0, bytes.Length)  

            Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRead))  

        Catch e As Exception  
            Console.WriteLine(e.ToString())  
        End Try  

        client.Close()  

        Return 0  
    End Function 'Main  
End Class 'TcpTimeClient  
using System;  
using System.Net.Sockets;  
using System.Text;  

public class TcpTimeClient {  
    private const int portNum = 13;  
    private const string hostName = "host.contoso.com";  

    public static int 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());  
        }  

        return 0;  
    }  
}  

TcpListener viene usato per monitorare una porta TCP per le richieste in ingresso e quindi creare un Socket o TcpClient che gestisce la connessione al client.TcpListener is used to monitor a TCP port for incoming requests and then create either a Socket or a TcpClient that manages the connection to the client. Il metodo Start abilita l'ascolto sulla porta e il metodo Stop lo disabilita.The Start method enables listening, and the Stop method disables listening on the port. Il metodo AcceptTcpClient accetta le richieste di connessione in ingresso e crea un TcpClient per gestire la richiesta e il metodo AcceptSocket accetta le richieste di connessione in ingresso e crea un Socket per gestire la richiesta.The AcceptTcpClient method accepts incoming connection requests and creates a TcpClient to handle the request, and the AcceptSocket method accepts incoming connection requests and creates a Socket to handle the request.

L'esempio seguente dimostra la creazione di un server di riferimento ora di rete con TcpListener per monitorare la porta TCP 13.The following example demonstrates creating a network time server using a TcpListener to monitor TCP port 13. Quando viene accettata una richiesta di connessione in ingresso, il server di riferimento ora risponde con la data e ora correnti dal server host.When an incoming connection request is accepted, the time server responds with the current date and time from the host server.

Imports System  
Imports System.Net.Sockets  
Imports System.Text  

Public Class TcpTimeServer  

    Private const portNum As Integer = 13  

    ' Entry point that delegates to C-style main Private Function.  
    Public Overloads Shared Sub Main()  
        System.Environment.ExitCode = _  
            Main(System.Environment.GetCommandLineArgs())  
    End Sub  

    Overloads Public Shared Function Main(args() As [String]) As Integer  
        Dim done As Boolean = False  

        Dim listener As New TcpListener(portNum)  

        listener.Start()  

        While Not done  
            Console.Write("Waiting for connection...")  
            Dim client As TcpClient = listener.AcceptTcpClient()  

            Console.WriteLine("Connection accepted.")  
            Dim ns As NetworkStream = client.GetStream()  

            Dim byteTime As Byte() = _  
                Encoding.ASCII.GetBytes(DateTime.Now.ToString())  

            Try  
                ns.Write(byteTime, 0, byteTime.Length)  
                ns.Close()  
                client.Close()  
            Catch e As Exception  
                Console.WriteLine(e.ToString())  
            End Try  
        End While  

        listener.Stop()  

        Return 0  
    End Function 'Main  
End Class 'TcpTimeServer  
using System;  
using System.Net.Sockets;  
using System.Text;  

public class TcpTimeServer {  

    private const int portNum = 13;  

    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;  
    }  

}  

Vedere ancheSee Also