TCP 服务

TCPClient 类使用 TCP 从 Internet 资源请求数据。TcpClient 的方法和属性提取某个 Socket 的创建细节,该实例用于通过 TCP 请求和接收数据。由于到远程设备的连接表示为流,因此可以使用 .NET Framework 流处理技术读取和写入数据。

TCP 协议建立与远程终结点的连接,然后使用此连接发送和接收数据包。TCP 负责确保将数据包发送到终结点并在数据包到达时以正确的顺序对其进行组合。

若要建立 TCP 连接,必须知道承载所需服务的网络设备的地址以及该服务用于通信的 TCP 端口。Internet 分配号码机构 (IANA) 定义公共服务的端口号(请访问 www.iana.org/assignments/port-numbers)。IANA 列表中所没有的服务可使用 1,024 到 65,535 这一范围中的端口号。
以下示例说明如何设置 TcpClient 以连接到 TCP 端口 13 上的时间服务器。

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 用于监视 TCP 端口上的传入请求,然后创建一个 SocketTcpClient 来管理与客户端的连接。Start 方法启用侦听,而 Stop 方法禁用端口上的侦听。AcceptTcpClient 方法接受传入的连接请求并创建 TcpClient 以处理请求,AcceptSocket 方法接受传入的连接请求并创建 Socket 以处理请求。

以下示例说明如何使用 TcpListener 创建网络时间服务器以监视 TCP 端口 13。当接受传入的连接请求时,时间服务器用来自宿主服务器的当前日期和时间进行响应。

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

原文地址:https://www.cnblogs.com/xh831213/p/330099.html