1

我在 UdpClient.BeginReceive 方法中收到“现有连接被远程主机强制关闭”错误。可能是什么问题?

此代码在网络中的某些 ip 中工作,但在某些 ip 中不起作用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Net.NetworkInformation;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    public struct scnHeader
    {
        public uint signature; // 0x19141287

        public ushort sequence; // unique sequence number per packet
        public byte count; // retry count for the same sequence
        public byte type; // packet type

        public ushort length; // length of data
        public byte protocol; // protocol type unique to scintilla
        public byte id; // unique value per protocol to identify a packet

        public byte medium; // type of medium
        public byte role; // registrant role type  
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public byte[] reserved1;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] serialNumber;// Unique device serial number
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
        public byte[] reserved2;
    }
    public struct scnPlugModifyReq
    {
        public scnHeader header; // id=102, type=1(req)
        public byte totalPlugs; // number of plugs returned in status
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
        public byte[] reserved1; // reserved            
        public uint plugMask; // Plug state change value
        public uint plugState;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public byte[] reserved2;
    }
    public struct scnPlugModifyRsp
    {
        public scnHeader header; // id=102, type=1(req)
        public byte totalPlugs; // number of plugs returned in status
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
        public byte[] reserved1; // reserved           
        public uint plugState;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
        public byte[] reserved2;
    }

    public class UdpState
    {
        public UdpClient u;
        public IPEndPoint e;
    }

    class Program
    {
        public static uint SwapUint(uint value)
        {
            return (uint)(((value & 0xFFU) << 24) | ((value >> 24) & 0xFFU)
                        | ((value & 0xFF00U) << 8) | ((value >> 8) & 0xFF00U));
        }


        public static ulong ReverseBytes2(ulong value)
        {
            return (value & 0x00000000000000FFUL) << 56 | (value & 0x000000000000FF00UL) << 40 |
                   (value & 0x0000000000FF0000UL) << 24 | (value & 0x00000000FF000000UL) << 8 |
                   (value & 0x000000FF00000000UL) >> 8 | (value & 0x0000FF0000000000UL) >> 24 |
                   (value & 0x00FF000000000000UL) >> 40 | (value & 0xFF00000000000000UL) >> 56;
        }

        public static ushort SwapUshort(ushort value)
        {
            return (ushort)(((value & 0xFFU) << 8) | ((value & 0xFF00U) >> 8));
        }
        public static scnPlugModifyReq tx7;
        public static scnPlugModifyRsp rx7;

        public static byte[] data;
        public static byte[] datar;
        public static Socket clientSocket;    


        public static byte[] getBytesfromstruct(object o)
        {
            int size = Marshal.SizeOf(o);
            byte[] arr = new byte[size];
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(o, ptr, true);
            Marshal.Copy(ptr, arr, 0, size);
            Marshal.FreeHGlobal(ptr);
            return arr;
        }
        public static object fromBytes(byte[] arr, object o)
        {
            object str = new object();
            int size = Marshal.SizeOf(o);
            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.Copy(arr, 0, ptr, size);
            o = (object)Marshal.PtrToStructure(ptr, o.GetType());
            Marshal.FreeHGlobal(ptr);
            return o;
        }
        public static void prescnPlugModifyReq()
        {
            tx7.header.count = 0x00;
            tx7.header.id = 0x65;
            tx7.header.length = Program.SwapUshort((ushort)Marshal.SizeOf(tx7));
            tx7.header.medium = 0x01;
            tx7.header.protocol = 0x01;
            tx7.header.reserved1 = new byte[] { 0x0, 0x0 };
            tx7.header.reserved2 = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
            tx7.header.role = 0x03;
            tx7.header.sequence = 0x0;
            tx7.header.serialNumber = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
            tx7.header.signature = Program.SwapUint((uint)0x19141287);
            tx7.header.type = 0x01;
            tx7.totalPlugs = 0x04;
            tx7.reserved1 = new byte[] { 0x0, 0x0, 0x0 };
            tx7.plugMask = Program.SwapUint(0);
            tx7.plugState = Program.SwapUint(0);
            tx7.reserved2 = new byte[] { 0x0, 0x0, 0x0, 0x0 };
        }

        public static bool messageReceived;
        public static IPEndPoint URJAIP;
        public static IPEndPoint Sender;
        public static byte[] send_buffer;
        public static byte[] recv_buffer;
        public static IPAddress[] UrjaDevices = new IPAddress[30];
        public static string myHost = System.Net.Dns.GetHostName();
        public static string myIP = Dns.GetHostByName(myHost).AddressList[0].ToString();
        public static int count;
        public static void sendPacket(object o, IPAddress[] addr, int port)
        {
            try
            {
                count = addr.Count(x => x != null);
                byte[] send_buffer = Program.getBytesfromstruct(o);          
                int i = 0;
                count = addr.Count(t => t != null);
            here1:
                messageReceived = false;
                while (i < count)
                {
                    UdpClient device = new UdpClient(addr[i].ToString(), port);
                    Sender = new IPEndPoint(IPAddress.Parse(myIP), 19012);
                    if (addr[i].ToString() == myIP)
                    {
                        i++;
                        continue;
                    };
                    int ret = device.Send(send_buffer, send_buffer.Length);

                    UdpState s = new UdpState();
                    s.u = device;
                    s.e = Sender;
                    device.BeginReceive(new AsyncCallback(recvPacket), s);//at this point I get exception which is have given at title
                    if (messageReceived == false)
                    {
                        Thread.Sleep(10);
                        i++;
                        goto here1;
                    }

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }

        }

        public static void recvPacket(IAsyncResult ar)
        {
            UdpClient dev = (UdpClient)((UdpState)(ar.AsyncState)).u;
            IPEndPoint sen = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
            Console.WriteLine("Message Received!{0}",dev.Client.RemoteEndPoint.ToString());
            messageReceived = true;
        }

        public static void Main()
        {
            prescnPlugModifyReq();
            byte[] data = getBytesfromstruct(tx7);
            IPAddress[] temp = new IPAddress[11];            
            temp[0] = IPAddress.Parse("192.168.1.1");
            temp[1] = IPAddress.Parse("192.168.1.100");
            temp[2] = IPAddress.Parse("192.168.1.111");
            temp[3] = IPAddress.Parse("192.168.1.200");
            temp[4] = IPAddress.Parse("192.168.1.9");
            temp[5] = IPAddress.Parse("192.168.1.10");
            temp[6] = IPAddress.Parse("192.168.1.106");
            temp[7] = IPAddress.Parse("192.168.1.112");
            temp[8] = IPAddress.Parse("192.168.1.110");
            temp[9] = IPAddress.Parse("192.168.1.109");
            temp[10] = IPAddress.Parse("192.168.1.105");  
            sendPacket(tx7,temp,19012);
            Console.ReadLine();          
        }                
    }
}
4

0 回答 0