C# UDP守护程序类:引用的对象类型不支持尝试的操作
我正在C#中创建一个UDP守护进程类,在Visual Studio中设置断点后,我看到“所引用的对象类型不支持尝试的操作”。在C# UDP守护程序类:引用的对象类型不支持尝试的操作,c#,sockets,C#,Sockets,我正在C#中创建一个UDP守护进程类,在Visual Studio中设置断点后,我看到“所引用的对象类型不支持尝试的操作”。在this::ip::Address::ScopeId::base中。ScopeId引发异常System.Net.Sockets.SocketException。错误代码为10045/不支持操作 呼叫代码: namespace Foo.Tester { class Program { static void Main(string[] arg
this::ip::Address::ScopeId::base
中。ScopeId引发异常System.Net.Sockets.SocketException
。错误代码为10045/不支持操作
呼叫代码:
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);
}
}
}
}
由于您希望在构造函数内使用端口,因此需要将其作为构造函数参数传递,而不是稍后进行设置,例如:
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);
}
....
未在
ip=new IPEndPoint(IPAddress.Any,port)中设置端口代码>这导致了套接字异常,所以这是我缺少的某种基本C#OO概念……啊,我现在明白了,ip是在对象实例的构造过程中分配的,而端口直到之后才分配。