UDP守护程序类:引用的对象类型不支持尝试的操作

时间:2011-04-06 11:19:49

标签: c# sockets

我在C#中创建UDP守护程序类,在Visual Studio中设置断点后,我看到“引用的对象类型不支持尝试的操作”。在this::ip::Address::ScopeId::base内。 ScopeId抛出异常System.Net.Sockets.SocketException。错误代码为10045 / OperationNotSupported。

致电代码:

namespace Foo.Tester
{
    class Program
    {
        static void Main(string[] args)
        {
            var TestDaemon = new UDPDaemon();
            TestDaemon.port = 9999;
            TestDaemon.Start();
            ...

UDPDaemon类:

{
    public class UDPDaemon
    {

        public int receivedDataLength; 
        public byte[] data; 
        public IPEndPoint ip; 
        public Socket socket; 
        public IPEndPoint sender;
        public EndPoint Remote; 
        public string raw;
        public int port { get; set; }
        public LogRow row;


        public UDPDaemon() 
        {
            ip = new IPEndPoint(IPAddress.Any, port);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sender = new IPEndPoint(IPAddress.Any, 0);
            Remote = (EndPoint)(sender);
        }
        public void Start()
        {
            socket.Bind(ip);
            while (true)
            {
                data = new byte[1024];
                receivedDataLength = socket.ReceiveFrom(data, ref Remote);
                raw = Encoding.ASCII.GetString(data, 0, receivedDataLength);
                row = new LogRow(raw);
                //Will eventually move to Queue, but just print it for now
                Console.WriteLine(row.ClientIp);
            }
        }
    }
}
  1. 导致此异常的原因是什么意思?
  2. 为什么我只在VS中设置断点时才会看到异常?
  3. 我刚刚开始学习这门语言,所以如果代码中有任何其他内容似乎很有用。

1 个答案:

答案 0 :(得分:1)

由于你想在构造函数中使用port,你需要将它作为构造函数参数传递,而不是稍后设置它,例如:

public class UDPDaemon
{
    public int receivedDataLength; 
    public byte[] data; 
    public IPEndPoint ip; 
    public Socket socket; 
    public IPEndPoint sender;
    public EndPoint Remote; 
    public string raw;
    public int Port { get; private set; }
    public LogRow row;

    public UDPDaemon(int port) 
    {
        Port = port;
        ip = new IPEndPoint(IPAddress.Any, port);
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        sender = new IPEndPoint(IPAddress.Any, 0);
        Remote = (EndPoint)(sender);
    }
 ....