BeginReceive() public method

public BeginReceive ( AsyncCallback requestCallback, object state ) : IAsyncResult
requestCallback AsyncCallback
state object
return IAsyncResult
Ejemplo n.º 1
0
        private void thread()
        {
            UdpClient ucl = new UdpClient(6000);
            IAsyncResult iar = ucl.BeginReceive(null, null);

            while (!exit)
            {
                if (!iar.AsyncWaitHandle.WaitOne(1000))
                    continue;

                IPEndPoint ep = new IPEndPoint(0, 0);
                byte[] data = ucl.EndReceive(iar, ref ep);
                iar = ucl.BeginReceive(null, 0);

                using (MemoryStream ms = new MemoryStream(data))
                {
                    BinaryReader br = new BinaryReader(ms);

                    while (ms.Position < ms.Length)
                    {
                        CanMessage m = CanMessage.DeserializeFrom(br);

                        if (MessageReceived != null)
                            MessageReceived(this, m);
                    }
                }
            }

            ucl.Close();
        }
Ejemplo n.º 2
0
        private void OnReceived(IAsyncResult ar)
        {
            if (Client != null)
            {
                IPEndPoint endpoint = new IPEndPoint((EndPoint as IPEndPoint).Address, 0);

                byte[] data;
                try
                {
                    data = Client.EndReceive(ar, ref endpoint);
                }
                catch (SocketException)
                {
                    Dispose();
                    return;
                }
                catch (ObjectDisposedException)
                {
                    Dispose();
                    return;
                }
                LastActivity = DateTime.UtcNow;
                Client.BeginReceive(new AsyncCallback(OnReceived), null);
                Reader.ReceivedData(data);
            }
        }
Ejemplo n.º 3
0
        public UDPListener(int port)
        {
            Port = port;
            queue = new Queue<byte[]>();
            ClosingEvent = new ManualResetEvent(false);
            callbackLock = new object();

            // try to open the port 10 times, else fail
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    receivingUdpClient = new UdpClient(port);
                    break;
                }
                catch (Exception)
                {
                    // Failed in ten tries, throw the exception and give up
                    if (i >= 9)
                        throw;

                    Thread.Sleep(5);
                }
            }
            RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            // setup first async event
            AsyncCallback callBack = new AsyncCallback(ReceiveCallback);
            receivingUdpClient.BeginReceive(callBack, null);
        }
Ejemplo n.º 4
0
    /// <summary>
    ///   Start listening on udp port
    /// </summary>
    public override void Start()
    {
      Log.Debug("PortUdp.start");

      try
      {
        Log.Debug("Start waiting for a connection...");
        _listen = true;


        var ip = GetLocalIp();
        var ep = new IPEndPoint(ip, _port);
        var u = new UdpClient();
        u.EnableBroadcast = true;
        u.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        u.Client.Bind(ep);
        _state = new UdpState();
        _state.e = ep;
        _state.u = u;
        u.BeginReceive(ReceiveCallback, _state);

        base.Start();
      }
      catch (Exception e)
      {
        Log.Error("PortUdp.Start error", e);
      }
    }
Ejemplo n.º 5
0
 /// <summary>
 /// Connect to specific remote end point and only send and receive from that endpoint.
 /// </summary>
 /// <param name="endPoint"></param>
 public void Connect(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint)
 {
     this.remoteEndPoint = remoteEndPoint;
     udp = new UdpClient(localEndPoint);
     receivingPending = true;
     udp.BeginReceive(new AsyncCallback(OnPacketReceived), this);
 }
Ejemplo n.º 6
0
        //udp通讯类byLeo
        #region
        public string[] UdpGetInfoByIPPort(string ipAddress, int ipPort, string cmdstr, int idelay)
        {
            if (basefun.IsCorrenctIP(ipAddress) == false) return null;
            if (idelay == 0) idelay = 100;
            int timeout = idelay;
            byte[] bytOutBuffer = getByteBy16s(cmdstr);
            IPEndPoint RemoteIpEndPoint = SetIPEndPoint(ipAddress, ipPort);
            if (RemoteIpEndPoint == null) return null;
            byte[] bytReceiveBuffer;
            using (UdpClient udpClient = new UdpClient())
            {
                udpClient.Send(bytOutBuffer, bytOutBuffer.Length, RemoteIpEndPoint);
                IPEndPoint from = new IPEndPoint(IPAddress.Any, 0);
                IAsyncResult result = udpClient.BeginReceive(null, this);
                result.AsyncWaitHandle.WaitOne(timeout, false);
                if (!result.IsCompleted)
                {
                    //throw SharpTimeoutException.Create(ipAddress, timeout);
                    udpClient.Close();
                    return null;
                }

                bytReceiveBuffer = udpClient.EndReceive(result, ref from);
                string udpInfo = get16sByByte(bytReceiveBuffer);
                udpInfo = SpecialRestore(udpInfo, "dddb", "db");
                udpInfo = SpecialRestore(udpInfo, "dcdb", "c0");
                //取返回值16进制数组,并解析
                string[] infos = AnalysisEateryResults(udpInfo);
                udpClient.Close();
                return infos;
            }

        }
 public ServerUDPTunnel(ServerPlayer player)
 {
     // enstablish an Connection
     this.player = player;
     udp = new UdpClient(new IPEndPoint(IPAddress.Any, Server.instance.UDPStartPort + (int)player.id));
     udp.BeginReceive(onReceive, null);
 }
Ejemplo n.º 8
0
		/// <summary>
		/// 构造一个新的消息对象,并绑定到指定的端口和IP上。
		/// </summary>
		/// <param name="ip">绑定的IP</param>
		/// <param name="port">绑定的端口</param>
		internal UDPThread(IPMClient ipmClient)
		{
			IsInitialized = false;
			try
			{
				client = new UdpClient(new IPEndPoint(ipmClient.Config.BindedIP, ipmClient.Config.Port));
			}
			catch (Exception)
			{
				OnNetworkError(new EventArgs());
				return;
			}
			SendList = new List<PackedNetworkMessage>();
			client.EnableBroadcast = true;
			_ipmClient = ipmClient;

			CheckQueueTimeInterval = 2000;
			MaxResendTimes = 5;
			new System.Threading.Thread(new System.Threading.ThreadStart(CheckUnConfirmedQueue)) { IsBackground = true }.Start();


			IsInitialized = true;

			//开始监听
			client.BeginReceive(EndReceiveDataAsync, null);
		}
Ejemplo n.º 9
0
        public ConnectionManager(int nPortListen)
        {
            listenPort = nPortListen;
            udpReceiver = new UdpClient(listenPort);

            udpReceiver.BeginReceive(new AsyncCallback(OnUdpReceived), udpReceiver);
        }
        public SearchSniffer()
        {
            IPAddress[] LocalAddresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            ArrayList temp = new ArrayList();
            foreach (IPAddress i in LocalAddresses) temp.Add(i);
            temp.Add(IPAddress.Loopback);
            LocalAddresses = (IPAddress[])temp.ToArray(typeof(IPAddress));

            for (int id = 0; id < LocalAddresses.Length; ++id)
            {
                try
                {
                    var localEndPoint = new IPEndPoint(LocalAddresses[id], 1900);
                    UdpClient ssdpSession = new UdpClient(localEndPoint);
                    ssdpSession.MulticastLoopback = false;
                    ssdpSession.EnableBroadcast = true;
                    if (localEndPoint.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ssdpSession.JoinMulticastGroup(UpnpMulticastV4Addr, LocalAddresses[id]);
                    }

                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                    ssdpSession.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

                    ssdpSession.BeginReceive(new AsyncCallback(OnReceiveSink), new object[] { ssdpSession, localEndPoint });
                    SSDPSessions[ssdpSession] = ssdpSession;
                }
                catch (Exception) { }
            }
        }
Ejemplo n.º 11
0
        private void ReceiveCallBack(IAsyncResult Asr)
        {
            if (_udpClient == null)
            {
                return;
            }
            byte[] dat = null;
            try
            {
                dat = _udpClient.EndReceive(Asr, ref _receivedEp);
            }
            catch (SocketException ex)
            {
                return;
            }
            catch (ObjectDisposedException ex)
            {
                return;
            }

            OnBytesReceived?.Invoke(dat);

            if (OnBytesReceived == null)
            {
                // store the data if callback is not set
                _mutex.WaitOne();
                _receivedPackets.AddLast(dat);
                _mutex.ReleaseMutex();
            }


            // 今一度非同期受信を開始
            _udpClient.BeginReceive(ReceiveCallBack, this);
        }
Ejemplo n.º 12
0
        //データを受信した時
        private void ReceiveCallback(IAsyncResult ar)
        {
            System.Net.Sockets.UdpClient udp = (System.Net.Sockets.UdpClient)ar.AsyncState;

            //非同期受信を終了する
            System.Net.IPEndPoint remoteEP = null;
            byte[] rcvBytes;
            try
            {
                rcvBytes = udp.EndReceive(ar, ref remoteEP);
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine("受信エラー({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socketは閉じられています。");
                return;
            }

            RecieveData(remoteEP.Address, remoteEP.Port, rcvBytes);


            //再びデータ受信を開始する
            udp.BeginReceive(ReceiveCallback, udp);
        }
Ejemplo n.º 13
0
 public Client()
 {
     IPEndPoint myEndPoint = new IPEndPoint(IPAddress, 8307);
     _udpClient = new UdpClient(myEndPoint);
     List<object> state = new List<object> { myEndPoint, _udpClient };
     _udpClient.BeginReceive(OnUdpDataReceived, state);
 }
Ejemplo n.º 14
0
        //データを受信した時
        private void ReceiveCallback(IAsyncResult ar)
        {
            System.Net.Sockets.UdpClient udp =
                (System.Net.Sockets.UdpClient)ar.AsyncState;

            //非同期受信を終了する
            System.Net.IPEndPoint remoteEP = null;
            byte[] rcvBytes;
            try
            {
                rcvBytes = udp.EndReceive(ar, ref remoteEP);
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine("Error({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socket closed");
                return;
            }

            //データを文字列に変換する
            string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes);
            var    e      = new UDP_ReceiveData(rcvMsg, remoteEP.Address.ToString());

            Console.WriteLine("datarecived:{0}", rcvMsg);
            packet_receive(this, e);

            //再びデータ受信を開始する
            udp.BeginReceive(ReceiveCallback, udp);
        }
Ejemplo n.º 15
0
        public void Initialize()
        {
            tcpServer = new TcpListener(IPAddress.Any, 1901);

            tcpServer.BeginAcceptTcpClient()

            sender = new UdpClient();

            sender.DontFragment = true;

            sender.JoinMulticastGroup(remoteEndPoint.Address);

            listener = new UdpClient();

            listener.ExclusiveAddressUse = false;

            listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            listener.ExclusiveAddressUse = false;

            listener.Client.Bind(anyEndPoint);

            listener.DontFragment = true;

            listener.JoinMulticastGroup(remoteEndPoint.Address);

            listener.BeginReceive(ReceiveCallback, null);
        }
Ejemplo n.º 16
0
        public void Discover()
        {
            m_endpoints = new HashSet<IPEndPoint>();
            //m_discover = new UdpClient(new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort));
            m_discover = new UdpClient();
            m_discover.EnableBroadcast = true;
            var endpoint = new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort);

            for (int i = 0; i < NumBroadcast; i++)
            {
                m_discover.Send(RemoteRunner.DiscoverPackage, RemoteRunner.DiscoverPackage.Length, endpoint);
                m_discover.BeginReceive(DiscoverCallback, null);
                Thread.Sleep(BroadcastDelay);
            }

            m_discover.Close();
            m_clients = new List<TcpClient>();

            foreach (var addr in m_endpoints)
            {
                Console.WriteLine(addr);
                var cl = new TcpClient();
                cl.BeginConnect(addr.Address, RemoteRunner.ConnectionPort, ConnectCallback, cl);
            }
        }
Ejemplo n.º 17
0
        public void StartServer()
        {
            //var client = new MiNetClient(new IPEndPoint(Dns.GetHostEntry("pe.mineplex.com").AddressList[0], 19132), "TheGrey");
            _serverTargetEndpoint = new IPEndPoint(Dns.GetHostEntry("yodamine.com").AddressList[0], 19135);
            //_serverTargetEndpoint = new IPEndPoint(IPAddress.Parse("147.75.194.126"), 19132);
            _serverListenerEndPoint = Endpoint = new IPEndPoint(IPAddress.Any, 19134);

            _listener = new UdpClient(Endpoint);
            _listener.Client.ReceiveBufferSize = int.MaxValue;
            _listener.Client.SendBufferSize = int.MaxValue;
            _listener.DontFragment = false;
            _listener.EnableBroadcast = false;

            // SIO_UDP_CONNRESET (opcode setting: I, T==3)
            // Windows:  Controls whether UDP PORT_UNREACHABLE messages are reported.
            // - Set to TRUE to enable reporting.
            // - Set to FALSE to disable reporting.

            uint IOC_IN = 0x80000000;
            uint IOC_VENDOR = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

            _listener.Client.IOControl((int) SIO_UDP_CONNRESET, new byte[] {Convert.ToByte(false)}, null);
            _listener.BeginReceive(ReceiveCallback, _listener);
        }
Ejemplo n.º 18
0
 public void beginReceivingUdp(int port)
 {
     client = new UdpClient(port);
     sourceIp = new IPEndPoint(IPAddress.Any, port);
     bool isComplete = true;
     IAsyncResult udpCallback = null;
     try
     {
         while (true)
         {
             if (isComplete)
             {
                 udpCallback = client.BeginReceive(new AsyncCallback(callback), null);
                 isComplete = false;
             }
             else
             {
                 if (udpCallback.IsCompleted == true) { isComplete = true; }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("W10.001.01 Exception during receiving of udp, Exception[" + ex + "]");
     }
 }
        public UPnPSearchSniffer()
        {
            IPAddress[] LocalAddresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            ArrayList temp = new ArrayList();
            foreach (IPAddress i in LocalAddresses) temp.Add(i);
            temp.Add(IPAddress.Loopback);
            LocalAddresses = (IPAddress[])temp.ToArray(typeof(IPAddress));

            for (int id = 0; id < LocalAddresses.Length; ++id)
            {
                try
                {
                    UdpClient ssdpSession = new UdpClient(new IPEndPoint(LocalAddresses[id], 0));
                    ssdpSession.EnableBroadcast = true;

                    if (!Utils.IsMono())
                    {
                        uint IOC_IN = 0x80000000;
                        uint IOC_VENDOR = 0x18000000;
                        uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                        ssdpSession.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
                    }

                    ssdpSession.BeginReceive(new AsyncCallback(OnReceiveSink), ssdpSession);
                    SSDPSessions[ssdpSession] = ssdpSession;
                }
                catch (Exception) { }
            }
        }
Ejemplo n.º 20
0
        private void OnPacketReceived(IAsyncResult ar)
        {
            if (udp != null)
            {
                lock (udp)
                {
                    receivingPending = false;
                    IPEndPoint remoteEP = null;
                    try
                    {
                        byte[] bytes = udp.EndReceive(ar, ref remoteEP);

                        if (bytes != null && bytes.Length > 0)
                        {
                            remoteEndPoint = remoteEP;
                            lock (packets)
                            {
                                bool first = packets.Count == 0;
                                packets.Add(bytes);
                                if (first)
                                {
                                    received.Set();
                                }
                            }
                            // begin another.
                            if (udp != null)
                            {
                                receivingPending = true;
                                udp.BeginReceive(new AsyncCallback(OnPacketReceived), this);
                            }
                        }
                    }
                    catch (SocketException ex)
                    {
                        // receive is forceably closed on send, so ignore that
                        if (ex.SocketErrorCode != SocketError.ConnectionReset)
                        {
                            //throw;
                        }
                    }
                    catch (Exception)
                    {
                        // perhaps it was closed...
                    }
                }
            }
        }
 protected EndPointReflector()
 {
     log.Debug("Create an EndPointReflector");
     keepGoing = true;
     udpClient = new UdpClient(endPointReflectorPort, AddressFamily.InterNetwork);
     log.DebugFormat("Start listening for an incoming request on port {0}", ((IPEndPoint) udpClient.Client.LocalEndPoint).Port);
     udpClient.BeginReceive(ReceiveCallback, null);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Connect to any remote machine that wants to send to the given local port.
 /// </summary>
 public void Connect(IPEndPoint localEndPoint)
 {
     this.localEndPoint = localEndPoint;
     udp = new System.Net.Sockets.UdpClient(localEndPoint);
     udp.Client.ReceiveBufferSize = 1000000;
     receivingPending             = true;
     udp.BeginReceive(new AsyncCallback(OnPacketReceived), this);
 }
Ejemplo n.º 23
0
        public override void Start()
        {
            if (Running)
                return;

            listener = new UdpClient(endpoint.Port);
            listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Connect to any remote machine that wants to send to the given local port.
 /// </summary>
 public void Connect(IPEndPoint localEndPoint)
 {
     this.localEndPoint = localEndPoint;
     udp = new System.Net.Sockets.UdpClient(localEndPoint);
     udp.Client.ReceiveBufferSize = 1000000;
     receivingPending = true;
     udp.BeginReceive(new AsyncCallback(OnPacketReceived), this);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the MulticastDnsClient class.
 /// </summary>
 public MulticastDnsClient()
 {
     _nextTransId = (ushort)new Random().Next();
     _transactions = new Dictionary<ushort, Transaction>();
     _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
     _udpClient.BeginReceive(ReceiveCallback, null);
     _cache = new Dictionary<string, Dictionary<RecordType, List<ResourceRecord>>>();
 }
Ejemplo n.º 26
0
        public AppLogic()
        {
            State = AppLogicState.WaitingForDropFile;

            m_udpFileReceiver = new UdpClient(UDP_LISTENER_PORT);
            m_udpFileReceiverResult = m_udpFileReceiver.BeginReceive(
                o => Program.WrapThreadSafeDelegate(this.UDPProtocol_0_1)(), null);
        }
Ejemplo n.º 27
0
 private void Init()
 {
     int udpServerPort = Convert.ToInt32(ConfigurationManager.AppSettings["UdpServerPort"]);
     _udpServer = new UdpClient(udpServerPort);
     Console.WriteLine(" S E R V E R   IS   S T A R T E D ");
     Console.WriteLine("* Waiting for Clients...");
     _udpServer.BeginReceive(DataReceived, _udpServer);
 }
Ejemplo n.º 28
0
        public MainWindow()
        {
            InitializeComponent();
            udpclient = new System.Net.Sockets.UdpClient(15000);
            udpclient.BeginReceive(receiveCallback, udpclient);

            this.receivedData = new System.IO.MemoryStream();

        }
Ejemplo n.º 29
0
 public void Start()
 {
     Port = Program.ServerConfiguration.QueryPort;
     Udp = new UdpClient(Port);
     UserList = new ConcurrentDictionary<IPEndPoint, QueryUser>();
     Timer = new Timer(ResetUserList, null, 0, 30000);
     CToken = new CancellationTokenSource();
     Udp.BeginReceive(HandleReceive, null);
 }
Ejemplo n.º 30
0
        public OscClient(IPEndPoint serverEndpoint)
        {
            _serverEndpoint = serverEndpoint;
            _udp = new UdpClient();
            _callback = new System.AsyncCallback(HandleReceive);
            _oscParser = new keijiro.Osc.Parser();

            _udp.BeginReceive(_callback, null);
        }
        public UdpClientContext()
        {
            BeginReceiveUPDserver = new AsyncCallback(OnBeginReceiveUPDserverFinished);

            UdpServerSearcher = new UdpClient(BroadcastServer.Port, AddressFamily.InterNetwork);
            UdpServerSearcher.JoinMulticastGroup(BroadcastServer.Address, 1); //1 router hops for just local network

            UdpServerSearcher.BeginReceive(BeginReceiveUPDserver, null);
        }
Ejemplo n.º 32
0
 public static void Connect()
 {
     UdpClient client = new UdpClient();
     ep = new IPEndPoint(IPAddress.Parse(Address), Port);
     client.Connect(ep);
     Byte[] data = Encoding.ASCII.GetBytes(requestType["Container"]);
     client.BeginSend(data, data.Length, new AsyncCallback(SendCallback), client);            
     client.BeginReceive(new AsyncCallback(ReceiveCallBack), client);            
 }
Ejemplo n.º 33
0
 public ConnectionManager(WebcamServer s)
 {
     server = s;
     camManager = new CameraManager();
     clients = new List<string>();
     udpSender = new UdpClient();
     udpListener = new UdpClient(1112);
     udpListener.BeginReceive(new AsyncCallback(OnReceive), udpListener);
 }
Ejemplo n.º 34
0
 private void connectButton_Click(object sender, EventArgs e)
 {
     connectButton.Enabled = false;
     recivePortTextBox.Enabled = false;
     int recivePortText = int.Parse(recivePortTextBox.Text);
     udpClientReciver = new UdpClient(recivePortText);//8989
     // ソケット非同期受信(System.AsyncCallback)
     asyncResult = udpClientReciver.BeginReceive(ReceiveCallback, udpClientReciver);
 }
Ejemplo n.º 35
0
        public void Listen()
        {
            m_discoverClient = new UdpClient(DiscoverPort);
            m_discoverClient.BeginReceive(DiscoverCallback, null);

            m_listener = new TcpListener(IPAddress.Any, ConnectionPort);
            m_listener.Start(10);
            m_listener.BeginAcceptTcpClient(AcceptCallback, null);
        }
Ejemplo n.º 36
0
 static UDPVideoShim()
 {
     try
     {
         client = new UdpClient(5600, AddressFamily.InterNetwork);
         client.BeginReceive(clientdata, client);
     }
     catch { }
 }
        public CommunicationHandler()
        {
            _client = new UdpClient(3007);
            _client.EnableBroadcast = true;
            _client.JoinMulticastGroup(IPAddress.Parse("224.109.108.107"));
            _client.BeginReceive(HandleClientPacketReceived, _client);

            CommsCallback = null;
        }
Ejemplo n.º 38
0
        //
        // UDP送受信関連
        //

        // UDP受信
        private void buttonStart_Click(object sender, EventArgs e)
        {
            //
            // 実施中→終了
            //
            if (udpClient_ != null)
            {
                udpClient_.Close();
                udpClient_ = null;
                // ボタン等
                change_ui(false);
                return;
            }

            //
            // 未実施→実施
            //

            // 送信元、送信先
            try
            {
                sourcePort_    = Int32.Parse(textBoxBindPort.Text);
                sendPort_      = Int32.Parse(textBoxSendPort.Text);
                sendIPAddress_ = IPAddress.Parse(textBoxSendIPAddress.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return; // 開始せず中断
            }

            try
            {
                //UdpClientを作成し、指定したポート番号にバインドする
                System.Net.IPEndPoint localEP =
                    new System.Net.IPEndPoint(
                        System.Net.IPAddress.Any, //sourceIPAddress_,
                        Int32.Parse(textBoxBindPort.Text)
                        );
                udpClient_ = new System.Net.Sockets.UdpClient(localEP);
                //非同期的なデータ受信を開始する
                udpClient_.BeginReceive(ReceiveCallback, udpClient_);
                // ボタン等
                change_ui(true);
            }
            catch (Exception ex)
            {
                if (udpClient_ != null)
                {
                    udpClient_.Close();
                }
                udpClient_ = null;

                MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void ReceiveData(IAsyncResult ar)
        {
            try
            {
                System.Net.Sockets.UdpClient listener = (System.Net.Sockets.UdpClient)ar.AsyncState;
                byte[] data = listener.EndReceive(ar, ref endpoint);
#endif
                if (data.Length < 16)
                {
                    return;//bad request
                }
                UdpTrackerMessage request = UdpTrackerMessage.DecodeMessage(data, 0, data.Length, MessageType.Request);

                switch (request.Action)
                {
                case 0:
                    ReceiveConnect((ConnectMessage)request);
                    break;

                case 1:
                    ReceiveAnnounce((AnnounceMessage)request);
                    break;

                case 2:
                    ReceiveScrape((ScrapeMessage)request);
                    break;

                case 3:
                    ReceiveError((ErrorMessage)request);
                    break;

                default:
                    throw new ProtocolException(string.Format("Invalid udp message received: {0}", request.Action));
                }
            }
            catch (Exception e)
            {
                Logger.Log(null, e.ToString());
            }
            finally
            {
                if (Running)
                {
#if NETSTANDARD1_5
                    result = await listener.ReceiveAsync();

                    ReceiveData(result, client);
#else
                    listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
#endif
                }
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Open udpClient and listen for the port from directed host
        /// </summary>
        /// <param name="remoteHost">Remote host to listen. Use IPAddress.Any if you listen to any host</param>
        /// <param name="localPort">listening port</param>
        /// <returns></returns>
        public int Open(string remoteHost, int localPort)
        {
            this._localPort = localPort;

            // Create UDP client
            _remotEndPoint = new IPEndPoint(IPAddress.Parse(remoteHost), localPort);
            _udpClient     = new System.Net.Sockets.UdpClient(_remotEndPoint);

            // 非同期受信を開始
            _udpClient.BeginReceive(ReceiveCallBack, this);

            return(0);
        }
Ejemplo n.º 41
0
 public void ReceiveMessages()
 {
     lock (this)
     {
         try
         {
             udpSend.BeginReceive(receiveCallback, udpReceiveState);
         }
         catch (SocketException)
         {
             //string.Format($"SocketException:{exception}");
         }
     }
 }
Ejemplo n.º 42
0
        public Form1()
        {
            InitializeComponent();
            UdpClient udpClient = new System.Net.Sockets.UdpClient(19851);

            //UdpClient udpServer = new System.Net.Sockets.UdpClient(19851);
            //udpClient.Connect(HOSTADDRESS, 19851);
            // udpServer.BeginReceive(requestCallbacServer, udpServer);
            udpClient.BeginReceive(requestCallbacClient, udpClient);
            Send = new Action <byte[]>(o =>
            {
                udpClient.SendAsync(o, o.Length, HOSTADDRESS, HOSTPORT);
            });
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Open udpClient and listen for the port from 'any host'
        /// </summary>
        /// <param name="localPort">listening port</param>
        /// <returns></returns>
        public int Open(int localPort)
        {
            _localPort = localPort;

            // UDPクライアントを作成
            _udpClient = new System.Net.Sockets.UdpClient(_localPort);

            // 送信先エンドポイント情報を作成
            _receivedEp = new IPEndPoint(IPAddress.Any, 0);

            // 非同期受信を開始
            _udpClient.BeginReceive(ReceiveCallBack, this);

            return(0);
        }
Ejemplo n.º 44
0
        private void RecvStart()
        {
            if (!udp_client_.Client.IsBound)
            {
                return;
            }

            /* 受信状態であれば無視 */
            if ((recv_task_ar_ != null) && (!recv_task_ar_.IsCompleted))
            {
                return;
            }

            /* 受信開始 */
            recv_task_ar_ = udp_client_.BeginReceive(RecvTaskComplete, udp_client_);
        }
Ejemplo n.º 45
0
        internal UDPNetState(IPEndPoint ep, int readBufferSize)
            : base(ep)
        {
            Reader = new TReader();
            Writer = new TWriter();

            LastActivity = DateTime.UtcNow;

            Client = new UdpClient();
            Client.Connect(ep);
            Writer.SetClient(Client);

            Client.BeginReceive(new AsyncCallback(OnReceived), null);

            Reader.OnDisconnect     += Dispose;
            Reader.OnBufferOverflow += Reader_OnBufferOverflow;

            OnConnected();
        }
        public override void Start()
#endif
        {
            if (Running)
            {
                return;
            }

            //TODO test if it is better to use socket directly
            //Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            listener = new System.Net.Sockets.UdpClient(endpoint.Port);
#if NETSTANDARD1_5
            var receive = await listener.ReceiveAsync();

            ReceiveData(receive, listener);
#else
            listener.BeginReceive(new AsyncCallback(ReceiveData), listener);
#endif
        }
Ejemplo n.º 47
0
    IEnumerator receive_loop()
    {
        var e = new System.Net.IPEndPoint(System.Net.IPAddress.Any, listenPort);
        var u = new System.Net.Sockets.UdpClient(e);

        u.EnableBroadcast = true;
        var s = new UdpState();

        s.e = e;
        s.u = u;
        for (;;)
        {
            received = false;
            u.BeginReceive(new System.AsyncCallback(ReceiveCallback), s);
            while (!received)
            {
                yield return(null);
            }
        }
    }
Ejemplo n.º 48
0
        private bool Receive(System.Net.Sockets.UdpClient client)
        {
            bool success = true;

            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                clientReceive.BeginReceive(new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                success = false;
                Console.WriteLine(e.ToString());
            }
            return(success);
        }
Ejemplo n.º 49
0
        //データを受信した時
        private void ReceiveCallback(IAsyncResult ar)
        {
            System.Net.Sockets.UdpClient udp =
                (System.Net.Sockets.UdpClient)ar.AsyncState;

            //非同期受信を終了する
            System.Net.IPEndPoint remoteEP = null;
            byte[] rcvBytes;
            try
            {
                rcvBytes = udp.EndReceive(ar, ref remoteEP);
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine("受信エラー({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socketは閉じられています。");
                return;
            }

            // 受信情報を控えておく(送信データに載せるため)
            // 受信データ
            lastRcvBytes_ = new byte[rcvBytes.Length];
            Array.Copy(rcvBytes, 0, lastRcvBytes_, 0, rcvBytes.Length);
            // 受信元
            lastRemoteEP_ = remoteEP;

            // 転送する
            SendUDP(sendIPAddress_, sendPort_); // 送信先に転送する場合

            //再びデータ受信を開始する
            udp.BeginReceive(ReceiveCallback, udp);
        }
Ejemplo n.º 50
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                System.Net.Sockets.UdpClient client = state.workSocket;

                // Read data from the remote device.
                byte[] bytesRead = client.EndReceive(ar, ref localEP);

                if (bytesRead.Length > 0)
                {
                    byte[] rd = new byte[bytesRead.Length];
                    Array.Copy(bytesRead, 0, rd, 0, bytesRead.Length);
                    if (MessageReceived != null)
                    {
                        MessageReceived(rd);
                    }

                    // Signal that all bytes have been received.
                    receiveDone.Set();

                    // Continue receiving data.
                    client.BeginReceive(new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    Disconnect();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Ejemplo n.º 51
0
        private void OnReceiveData(IAsyncResult asyncResult)
        {
            System.Net.Sockets.UdpClient conn = (System.Net.Sockets.UdpClient)asyncResult.AsyncState;
            try
            {
                System.Net.IPEndPoint ep = new IPEndPoint(System.Net.IPAddress.Any, 0);
                byte[] local_buffer;
                int    rx = 0;

                try
                {
                    local_buffer = conn.EndReceive(asyncResult, ref ep);
                    rx           = local_buffer.Length;
                }
                catch (Exception) // ICMP port unreachable
                {
                    //restart data receive
                    conn.BeginReceive(OnReceiveData, conn);
                    return;
                }

                if (rx < 14)    // Sure it's too small
                {
                    //restart data receive
                    conn.BeginReceive(OnReceiveData, conn);
                    return;
                }

                try
                {
                    int Offset = 0;
                    Encapsulation_Packet Encapacket = new Encapsulation_Packet(local_buffer, ref Offset, rx);
                    //verify message
                    if (Encapacket.IsOK)
                    {
                        if (EncapMessageReceived != null)
                        {
                            EncapMessageReceived(this, local_buffer, Encapacket, Offset, rx, ep);
                        }
                    }
                    else
                    {
                        SequencedAddressItem Itempacket = new SequencedAddressItem(local_buffer, ref Offset, rx);
                        if (Itempacket.IsOK && (ItemMessageReceived != null))
                        {
                            ItemMessageReceived(this, local_buffer, Itempacket, Offset, rx, ep);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception in udp recieve: " + ex.Message);
                }
                finally
                {
                    //restart data receive
                    conn.BeginReceive(OnReceiveData, conn);
                }
            }
            catch (Exception ex)
            {
                //restart data receive
                if (conn.Client != null)
                {
                    Trace.TraceError("Exception in Ip OnRecieveData: " + ex.Message);
                    conn.BeginReceive(OnReceiveData, conn);
                }
            }
        }
Ejemplo n.º 52
0
 public static void Start()
 {
     Socket.Client.Bind(new IPEndPoint(IPAddress.Any, 1337));
     Socket.BeginReceive(ReceiveUDP, null);
 }
Ejemplo n.º 53
0
        //データを受信した時
        private void ReceiveCallback(IAsyncResult ar)
        {
            System.Net.Sockets.UdpClient udp =
                (System.Net.Sockets.UdpClient)ar.AsyncState;

            //非同期受信を終了する
            System.Net.IPEndPoint remoteEP = null;
            byte[] rcvBytes;
            try
            {
                rcvBytes = udp.EndReceive(ar, ref remoteEP);
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine("受信エラー({0}/{1})",
                                  ex.Message, ex.ErrorCode);
                return;
            }
            catch (ObjectDisposedException ex)
            {
                //すでに閉じている時は終了
                Console.WriteLine("Socketは閉じられています。");
                return;
            }

            // 処理対象?
            DhcpPacket rcv_packet = new DhcpPacket(rcvBytes);
            Boolean    reply      = this.dhcplease_.AutoReply(rcv_packet.chaddr_);
            Boolean    match      = this.dhcplease_.Matches(rcv_packet.chaddr_);

            {
                // 受信情報を控えておく(送信データに載せるため)
                // 受信データ
                lastRcvBytes_ = new byte[rcvBytes.Length];
                Array.Copy(rcvBytes, 0, lastRcvBytes_, 0, rcvBytes.Length);
                // 受信元
                lastRemoteEP_ = remoteEP;
            }

            //データを文字列に変換する
            string rcvMsg = "0x" + rcv_packet.xid_.ToString("X4") + ", " + rcv_packet.message_type_;

            //受信したデータと送信者の情報をRichTextBoxに表示する
            string displayMsg = string.Format("{0} [{1} ({2})] < {3}",
                                              DateTime.Now.ToString("HH:mm:ss.fff"), remoteEP.Address, remoteEP.Port, rcvMsg);

            textBoxRcvData.BeginInvoke(
                new Action <string>(ShowReceivedString), displayMsg);

            // 応答する
            if (match && (!reply))
            {
                // 当該MACアドレスが登録されていて、
                // かつ、「自動応答」が明示的にOFFされている場合は応答しない
            }
            else
            {
                // それ以外は応答する

                // 送信先のIPアドレスは remoteEP.Address ではなく、ブロードキャスト
                SendUDP(sourceIPAddress_, sourcePort_, IPAddress.Broadcast, remoteEP.Port);
            }

            //再びデータ受信を開始する
            udp.BeginReceive(ReceiveCallback, udp);
        }
Ejemplo n.º 54
0
 void StartRecv()
 {
     //	gr: does this throw if socket unreachable/closed?
     var RecvAsync = Socket.BeginReceive(new System.AsyncCallback(Recv), null);
 }
Ejemplo n.º 55
0
 /// <summary>
 /// Begins the receive.
 /// </summary>
 internal void BeginReceive()
 {
     mUdpClient.BeginReceive(new AsyncCallback(Callback), null);
 }