Networking - 通过端口发送的字节数

时间:2013-03-27 12:27:09

标签: c# networking port packet

我在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();
        }
    }
}

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

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

1 个答案:

答案 0 :(得分:1)

有几种可能性。首先,您可以在套接字上调用Accept并使程序阻塞,直到数据可用。只要数据可用,您就可以将Receive数据转换为字节数组并进行处理。

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

请参阅C#中的documentation套接字。