我在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);
}
}
}
}
答案 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);
}
....