日期:2011-02-11  浏览次数:20429 次

使用.NET访问 Internet(3) Paul_Ni(原作)

作者:中国资讯网 来源:zixuen.com 加入时间:2005-5-12 www.zixuen.com

使用 TCP 服务


TCPClient 类使用 TCP 从 Internet 资源请求数据。TcpClient 的方法和属性提取某个 Socket 实例的创建细节,该实例用于通过 TCP 请求和接收数据。由于到远程设备的连接表示为流,因此可以使用 .NET 框架流处理技术读取和写入数据。
TCP 协议建立与远程终结点的连接,然后使用此连接发送和接收数据包。TCP 负责确保将数据包发送到终结点并在数据包到达时以正确的顺序对其进行组合。
若要建立 TCP 连接,必须知道承载所需服务的网络设备的地址以及该服务用于通讯的 TCP 端口。Internet 分配号码机构 (Internet Assigned Numbers Authority, IANA) 定义公共服务的端口号(请访问 http://www.iana.org/assignments/port-numbers)。IANA 列表中所没有的服务可使用 1,024 到 65,535 这一范围中的端口号。
下列代码说明如何设置 TcpClient 以连接到 TCP 端口 13 上的时间服务器。
[C#]
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。当接受传入的连接请求时,时间服务器用来自宿主服务器的当前日期和时间进行响应。
[C#]
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.ToStr