网络-通过端口发送的字节数



我有以下c#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Networking
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("---Connecting to a Host using a Specific Port---");
            Console.WriteLine();
            Console.WriteLine("Attempting Connection...");
            Console.WriteLine();
            string hostname = "www.yahoo.com";
            int port_no = 21; //HTTP = 80, HTTPS = 443, FTP = 21
            IPAddress ipa = (IPAddress)Dns.GetHostAddresses(hostname)[0];
            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipa, port_no);
                if (socket.Connected == true)
                {
                    Console.WriteLine("The connection was successful!");
                }
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                if (ex.ErrorCode == 10061)
                {
                    Console.WriteLine("The connection was NOT successful!");
                }
                else
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.WriteLine();
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

如您所见,该程序试图使用特定的端口号连接到特定的网站。

如何修改程序,以便我可以知道连接后是否正在通过特定端口发送数据?或者计算发送的字节数或者文件类型?谢谢:)

有几种可能性。首先,您可以调用套接字上的Accept,并使程序阻塞,直到数据可用为止。一旦数据可用,您就可以将数据Receive到字节数组中并对此进行处理。

其次,你可以调用BeginAccept,异步等待数据到达,并相应地处理。

最新更新