当前位置: 首页>>代码示例>>C#>>正文


C# UdpClient.Receive方法代码示例

本文整理汇总了C#中System.Net.Sockets.UdpClient.Receive方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.Receive方法的具体用法?C# UdpClient.Receive怎么用?C# UdpClient.Receive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.UdpClient的用法示例。


在下文中一共展示了UdpClient.Receive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: serverLoop

        protected void serverLoop()
        {
            Trace.WriteLine("Waiting for UDP messages.");
            listener = new UdpClient(UDP_PORT);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_PORT);
            byte[] receive_byte_array;

            bool running = true;
            while (running)
            {
                try
                {
                    receive_byte_array = listener.Receive(ref groupEP);
                    if (receive_byte_array.Length != 2)
                    {
                        Trace.WriteLine("Invalid UDP message received. Ignored message!");
                        continue;
                    }

                    Trace.WriteLine("Upp fan speed message received.");
                    int fan = receive_byte_array[0];
                    byte speed = receive_byte_array[1];
                    fanControlDataObject.setPinSpeed(fan, speed, true);
                }
                catch
                {
                    running = false;
                }
            }
        }
开发者ID:futjikato,项目名称:ArduinoFanControl,代码行数:30,代码来源:FanUdpServer.cs

示例2: Main

    static void Main(string[] args)
    {
      byte[] data = new byte[1024];
      IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 19511);
      UdpClient newsock = new UdpClient(ipep);

      Console.WriteLine("Waiting for a client...");

      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

      data = newsock.Receive(ref sender);

      Console.WriteLine("Message received from {0}:", sender.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));

      string welcome = "Welcome to my test server";
      data = Encoding.ASCII.GetBytes(welcome);
      newsock.Send(data, data.Length, sender);

      while (true)
      {
        data = newsock.Receive(ref sender);

        Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
        newsock.Send(data, data.Length, sender);
      }
    }
开发者ID:HongSeokHwan,项目名称:legacy,代码行数:27,代码来源:Program.cs

示例3: GetServerChallengeSync

        public ServerPlayers GetServerChallengeSync(GetServerInfoSettings settings)
        {
            var localEndpoint = new IPEndPoint(IPAddress.Any, 0);
            using (var client = new UdpClient(localEndpoint))
            {
                client.Client.ReceiveTimeout = settings.ReceiveTimeout;
                client.Client.SendTimeout = settings.SendTimeout;

                client.Connect(EndPoint);

                var requestPacket = new List<byte>();
                requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 });
                requestPacket.AddRange(BitConverter.GetBytes(-1));

                client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length);
                byte[] responseData = client.Receive(ref localEndpoint);
                requestPacket.Clear();
                requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 });
                requestPacket.AddRange(responseData.Skip(5).Take(4));
                client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length);
                responseData = client.Receive(ref localEndpoint);

                return ServerPlayers.Parse(responseData);
            }
        }
开发者ID:svargy,项目名称:arma3beclient,代码行数:25,代码来源:Server.cs

示例4: Reciver

        public Reciver(string portString,HlavneOkno ho)
        {
            this.ho = ho;
            int port = 0;
            if (Int32.TryParse(portString, out port)==false)
            {
                return;
            }
            socket = new UdpClient(port);
            IPEndPoint server = new IPEndPoint(IPAddress.Any, port);

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    byte[] packet = socket.Receive(ref server);
                    ocakavany = Int32.Parse(Encoding.ASCII.GetString(packet).Substring(4, 4));
                    pocet++;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                sprava = new String[ocakavany];
                Thread.Sleep(20);
                while (nacitavaj)
                {
                    try
                    {
                        byte[] packet = socket.Receive(ref server);
                        String Sprava = Encoding.ASCII.GetString(packet).Substring(4,packet.Length-4);
                        Int32 poradie = Int32.Parse(Encoding.ASCII.GetString(packet).Substring(0,4));
                        sprava[poradie] = Sprava;
                        pocet++;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    Thread.Sleep(20);
                    if (pocet == ocakavany)
                    {
                        ho.pocuvatStop_Click();
                        break;
                    }
                }
            }, null);
        }
开发者ID:rasto28,项目名称:UDP-comunicator,代码行数:48,代码来源:Reciver.cs

示例5: Receive

		/// <summary>
		/// Attempts to receive a packet.
		/// </summary>
		/// <param name="client">the UDP client to receive from</param>
		/// <returns>the length of the received packet or -1 if nothing was received</returns>
		/// 
		public int Receive(UdpClient client)
		{
			source = new IPEndPoint(IPAddress.Any, 0);

			idx    = 0;
			data   = null;
			id     = -1;
			length = 0;
			try
			{
				data    = client.Receive(ref source);
				length  = data.Length - 4;
				id      = GetInt16();
				int len = GetInt16();
				if ( len != length )
				{
					Debug.LogWarning("Packet length mismatch (" + length + " received, " + len + " announced)");
				}
				errorCounter = 0;
			}
			catch (SocketException e)
			{
				if (errorCounter == 0)
				{
					Debug.LogWarning("Exception while waiting for MoCap server response (Time: " + Time.timeSinceLevelLoad + "s): " + e.Message);
				}
				errorCounter++;
			}

			return (data == null) ? -1 : length;
		}
开发者ID:stefanmarks,项目名称:MotionServer_Clients,代码行数:37,代码来源:NatNetPacket.cs

示例6: locateNS

	public static NameServerProxy locateNS(string host, int port) {
		if(host!=null) {
			if(port==0)
				port=Config.NS_PORT;
			NameServerProxy proxy=new NameServerProxy(host, port);
			proxy.ping();
			return proxy;
		}
		if(port==0)
			port=Config.NS_BCPORT;
		
		IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Broadcast, port);
		using(UdpClient udpclient=new UdpClient()) {
			udpclient.Client.ReceiveTimeout = 2000;
			udpclient.EnableBroadcast=true;
			byte[] buf=Encoding.ASCII.GetBytes("GET_NSURI");
			udpclient.Send(buf, buf.Length, ipendpoint);
			IPEndPoint source=null;
			try {
				buf=udpclient.Receive(ref source);
			} catch (SocketException) {
				// try localhost explicitly (if host wasn't localhost already)
				if(host==null || (!host.StartsWith("127.0") && host!="localhost"))
					return locateNS("localhost", Config.NS_PORT);
				else
					throw;
			}
			string location=Encoding.ASCII.GetString(buf);
			return new NameServerProxy(new PyroURI(location));
		}
	}
开发者ID:davies,项目名称:Pyrolite,代码行数:31,代码来源:NameServerProxy.cs

示例7: BeginProcessing

        /// <summary>
        /// Provides a one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessing()
        {
            // Initialize parameters and base Incog cmdlet components
            this.InitializeComponent();

            // Invoke Interative Mode if selected
            if (this.Interactive) this.InteractiveMode();

            // Receiving messages endpoint
            IPEndPoint bobEndpoint = new IPEndPoint(this.LocalAddress, 53);

            // Sending messages endpoing
            IPEndPoint aliceEndpoint = new IPEndPoint(this.RemoteAddress, 0);

            // Open up the UDP port for packet capture
            UdpClient socket = new UdpClient(bobEndpoint);
            this.packetCapturing = true;

            do
            {
                byte[] payload = socket.Receive(ref aliceEndpoint);
                string text = System.Text.Encoding.ASCII.GetString(payload);
                this.ReceiveCovertMessage(text);
            }
            while (this.packetCapturing);

            socket.Close();
        }
开发者ID:SimWitty,项目名称:Incog,代码行数:31,代码来源:ReceiveIncogLookup.cs

示例8: Listen

        public static void Listen(IPEndPoint remoteIP)
        {
            var done = false;

            var listener = new UdpClient(remoteIP);
            listener.Connect(remoteIP);
            var groupEP = new IPEndPoint(IPAddress.Any, remoteIP.Port);
            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast..");
                    byte[] bytes = listener.Receive(ref groupEP);
                    string json = EncodingUtility.Decode(bytes);
                    Console.WriteLine("Received broadcast from {0}:{1} :\n {2}\n", groupEP.Address,groupEP.Port, json);
                    var message = JsonHelper.JsonDeserialize<ExchangeAMd>(json);
                    //Do aaync
                    ProcessOrder(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
开发者ID:sathley,项目名称:Market-Data-Dissemination,代码行数:29,代码来源:Client.cs

示例9: SendBytesNow_LoopBack_SequenceNumber16K

        public void SendBytesNow_LoopBack_SequenceNumber16K()
        {
            int i;
            bool result = false;

            UDPSender us = new UDPSender("127.0.0.1", 7770);

            byte[] data = new byte[1024 * 16];

            for (i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            UdpClient listener = new UdpClient(7770);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 7770);

            //Blocking Call
            us.SendBytesNow(data, 1024 * 16);

            //BLOCKING CALL
            byte[] bytes = listener.Receive(ref groupEP);

            for (i = 0; i < data.Length; i++)
            {
                if (bytes[i] != (byte)i)
                {
                    Assert.True(false);
                }
            }

            Assert.True(true);

            listener.Close();
        }
开发者ID:jpadillak,项目名称:Concordia_Capstone2013-14,代码行数:35,代码来源:UDPSenderTests.cs

示例10: Main

        static void Main(string[] args)
        {
            System.Net.Sockets.UdpClient sock = new System.Net.Sockets.UdpClient();
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("129.241.187.44"), 20004);

            Console.WriteLine("Enter message");
            string userinput = Console.ReadLine();
            byte[] data = Encoding.ASCII.GetBytes(userinput);
            sock.Send(data, data.Length, iep);
            sock.Close();

            Console.WriteLine("Message sent.");



            System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(20004);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            byte[] recvdata = new byte[1024];
            recvdata = server.Receive(ref sender);
            server.Close();
            string stringData = Encoding.ASCII.GetString(recvdata, 0, recvdata.Length);
            Console.WriteLine("Response from " + sender.Address + Environment.NewLine + "Message: " + stringData);
            Console.ReadLine();

        }
开发者ID:lepaulse,项目名称:TTK4145-SANNTIDSPROGR-VAAR-2016,代码行数:25,代码来源:Program.cs

示例11: listen

        private void listen()
        {
            UdpClient uc = new UdpClient(9527);
            while (true)
            {
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0);
                byte[] bmsg = uc.Receive(ref ipep);
                string msg = Encoding.Default.GetString(bmsg);
                string[] s = msg.Split('|');
                if (s[0] == "PUBLIC")
                {
                   this.txtHistory.Text += s[2] +":"+ "\r\n";
                   this.txtHistory.Text += s[1] + "\r\n";

                }
                else if (s[0] == "INROOM")
                {
                    this.txtHistory.Text += s[1] + "登录了" + "\r\n";
                }
                else
                {
                    return;
                }

            }
        }
开发者ID:hytcchenqiuyang,项目名称:chatonline,代码行数:26,代码来源:FrmMain.cs

示例12: Main

        static void Main(string[] args)
        {
            String s;
            byte[] data;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 1165);
            UdpClient client = new UdpClient(ipep);
            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            String c;
            byte[] cdata;
            IPEndPoint cipep = new IPEndPoint(IPAddress.Any, 1166);
            UdpClient Cclient = new UdpClient(cipep);
            Cclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            while (true)
              {
              data = client.Receive(ref ipep);
              s = Encoding.ASCII.GetString(data);
              Console.WriteLine(s.Substring(35,75));//only what we need to see

              //don't need the console stuff right now...
              //cdata = Cclient.Receive(ref cipep);
              //c = Encoding.ASCII.GetString(cdata);
              //Console.ReadLine(); //this will pause the console
              //Console.WriteLine(c); //we dont want to do this quite yet
            }
        }
开发者ID:Willster419,项目名称:1073DataRecieverConsole,代码行数:26,代码来源:Program.cs

示例13: StartListener

        public static void StartListener(int port)
        {
            UdpClient client = new UdpClient();

                        client.ExclusiveAddressUse = false;
            IPEndPoint localEp = new IPEndPoint(IPAddress.Any, port);

                        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                        client.ExclusiveAddressUse = false;

                        client.Client.Bind(localEp);

                        //IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
                        //client.JoinMulticastGroup(multicastaddress);

                        while (true)
                        {
                            Byte[] data = client.Receive(ref localEp);

                            string strData = Encoding.ASCII.GetString(data);

                eventH e = JsonConvert.DeserializeObject<eventH>(strData);
                e.handle();

                        }
        }
开发者ID:jarrin,项目名称:OTM-Client,代码行数:26,代码来源:UDPLink.cs

示例14: Receiver

        public static void Receiver()
        {
            // Создаем UdpClient для чтения входящих данных
            UdpClient receivingUdpClient = new UdpClient(localPort);

            IPEndPoint RemoteIpEndPoint = null;

            try
            {
                Console.WriteLine(
                   "\n-----------*******Общий чат*******-----------");

                while (true)
                {
                    // Ожидание дейтаграммы
                    byte[] receiveBytes = receivingUdpClient.Receive(
                       ref RemoteIpEndPoint);

                    // Преобразуем и отображаем данные
                    Console.WriteLine(RemoteIpEndPoint.Address.ToString());
                    Console.WriteLine(RemoteIpEndPoint.Port.ToString());
                    string returnData = Encoding.UTF8.GetString(receiveBytes);
                    Console.WriteLine(" --> " + returnData.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n  " + ex.Message);
            }
        }
开发者ID:test08,项目名称:udp_chat,代码行数:30,代码来源:Program.cs

示例15: listen

        private void listen()
        {
            UdpClient uc = new UdpClient(9527);
            while (true)
            {
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
                byte[] bmsg = uc.Receive(ref ipep);
                string scontent = Encoding.Default.GetString(bmsg);
                string[] data = scontent.Split('|');
                if(data[0]=="INROOM")
                {
                    this.txt_person.Text += data[1] + "上线了\r\n";
                }
                if(data[0]=="PUBLIC")
                {
                    int l = data.Count();
                    if(l>3)
                    {
                        this.txtHistory.Text += data[2] + ":\r\n";
                        this.txtHistory.Text += data[2] + "\r\n";
                    }
                }

            }
        }
开发者ID:hytcshiyue,项目名称:C,代码行数:25,代码来源:FrmMain.cs


注:本文中的System.Net.Sockets.UdpClient.Receive方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。