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


C# UdpClient.Receive方法代码示例

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


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

示例1: ReceiveData

    // receive thread
    private void ReceiveData()
    {
        client = new UdpClient();

        IPEndPoint localEp = new IPEndPoint(IPAddress.Any, port);
        client.Client.Bind(localEp);

        client.JoinMulticastGroup(IPAddress.Parse(MULTICAST_ADDR));
        while (true)
        {
            try
            {
                byte[] data = client.Receive(ref localEp);
                string text = Encoding.UTF8.GetString(data);
                string[] message = text.Split(',');
                Vector3 result = new Vector3(float.Parse(message[0]), float.Parse(message[1]), float.Parse(message[2]));

                print(">> " + result);

                lastReceivedUDPPacket = result;
            }
            catch (Exception err)
            {
                print(err.ToString());
            }
        }
    }
开发者ID:intel-cornellcup,项目名称:mini-modbot-simulation,代码行数:28,代码来源:UDPReceive.cs

示例2: Main

    public static void Main()
    {
        byte[] data = new byte[1024];
          	string input, stringData;
          	UdpClient server = new UdpClient("127.0.0.1", 9877);

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

        string welcome = "Hello, are you there?";
        data = Encoding.ASCII.GetBytes(welcome);
        server.Send(data, data.Length);

        data = server.Receive(ref sender);

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

        while(true){
            input = Console.ReadLine();
            if (input == "exit")
                break;

                server.Send(Encoding.ASCII.GetBytes(input), input.Length);
             	data = server.Receive(ref sender);
        }
        Console.WriteLine("Stopping client");
        server.Close();
    }
开发者ID:Kaerit,项目名称:IsoMonksComm,代码行数:29,代码来源:client.cs

示例3: Main

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

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

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

          data = newsock.Receive(ref sender);

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

          string msg = Encoding.ASCII.GetString(data, 0, data.Length);
          data = Encoding.ASCII.GetBytes(msg);
          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:Kaerit,项目名称:IsoMonksComm,代码行数:26,代码来源:server.cs

示例4: Main

   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      UdpClient udpClient = new UdpClient("127.0.0.1", 9999);

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

      string welcome = "Hello";
      data = Encoding.ASCII.GetBytes(welcome);
      udpClient.Send(data, data.Length);

      data = udpClient.Receive(ref sender);

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

      while(true)
      {
         input = Console.ReadLine();
         udpClient.Send(Encoding.ASCII.GetBytes(input), input.Length);
         data = udpClient.Receive(ref sender);
         stringData = Encoding.ASCII.GetString(data, 0, data.Length);
         Console.WriteLine(stringData);
      }
      udpClient.Close();
   }
开发者ID:EdiCarlos,项目名称:MyPractices,代码行数:28,代码来源:udpclient.cs

示例5: FuncRcvData

    private void FuncRcvData()
    {
        client = new UdpClient (port);
        client.Client.ReceiveTimeout = 300; // msec
        client.Client.Blocking = false;
        while (stopThr == false) {
            try {
                IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = client.Receive(ref anyIP);
                string text = Encoding.ASCII.GetString(data);
                lastRcvd = text;

                if (lastRcvd.Length > 0) {
                    Thread.Sleep(delay_msec);
                    client.Send(data, data.Length, anyIP); // echo
                }
            }
            catch (Exception err)
            {
                //              print(err.ToString());
            }

            // without this sleep, on adnroid, the app will not start (freeze at Unity splash)
            Thread.Sleep(20); // 200
        }
        client.Close ();
    }
开发者ID:yasokada,项目名称:unity-150829-udpEcho,代码行数:27,代码来源:UdpEchoServer.cs

示例6: StartListener

    public void StartListener()
    {
        bool done = false;

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

        try
        {
            while (!done)
            {
                Console.WriteLine("Waiting for broadcast");
                byte[] bytes = listener.Receive( ref groupEP);

                Console.WriteLine("Received broadcast from {0} :\n {1}\n",
                    groupEP.ToString(),
                    Encoding.ASCII.GetString(bytes,0,bytes.Length));
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }
开发者ID:eraumotorsports,项目名称:carLogger,代码行数:29,代码来源:BroadcastListener.cs

示例7: Main

    public static void Main()
    {
        string addr = "127.0.0.1";
        int port = 7980;
        short cmd = 1;
        short seq = 0;
        string msg = "Hello";
        byte[] payload = Encoding.ASCII.GetBytes(msg);
        byte[] packet = Packet.Create(cmd, seq, payload);

        UdpClient udp = new UdpClient();
        var ip = IPAddress.Parse(addr);
        IPEndPoint ep = new IPEndPoint(ip, port);
        udp.Connect(ep);

        // send
        udp.Send(packet, packet.Length);

        // receive
        bool done = false;
        while (!done) {
            if (udp.Available <= 0) {
                IPEndPoint ep2 = new IPEndPoint(0, 0);
                byte[] packet2 = udp.Receive(ref ep2);

                Console.WriteLine("packet size: {0}", packet2.Length);

                Dictionary<string, object> parsed = Packet.Parse(packet2);
                foreach (KeyValuePair<string, object> item in parsed) {
                    Console.WriteLine("Received:{0} = {1}", item.Key, item.Value);
                }
                done = true;
            }
        }
    }
开发者ID:voltrue2,项目名称:gracenode,代码行数:35,代码来源:Test.cs

示例8: Main

 public static int Main()
 {
     bool done = false;
     UdpClient listener = new UdpClient(listenPort);
     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
     string received_data;
     byte[] receive_byte_array;
     try
     {
         while (!done)
         {
             Console.WriteLine("Waiting for broadcast");
             // this is the line of code that receives the broadcase message.
             // It calls the receive function from the object listener (class UdpClient)
             // It passes to listener the end point groupEP.
             // It puts the data from the broadcast message into the byte array
             // named received_byte_array.
             // I don't know why this uses the class UdpClient and IPEndPoint like this.
             // Contrast this with the talker code. It does not pass by reference.
             // Note that this is a synchronous or blocking call.
             receive_byte_array = listener.Receive(ref groupEP);
             Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
             received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
             Console.WriteLine("data follows \n{0}\n\n", received_data);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
     listener.Close();
     return 0;
 }
开发者ID:Lrss,项目名称:P3,代码行数:33,代码来源:Program.cs

示例9: StartListener

    private static void StartListener()
    {
        //Initiate UDP server
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        UdpClient listener = new UdpClient(ListenPort);
        IPEndPoint groupEp = new IPEndPoint(IPAddress.Any,ListenPort);
        IPEndPoint responseEp;
        string receivedCommand;

        try
        {
            while (true)
            {
                //Wait for incoming command
                Console.WriteLine("Waiting for command");
                byte[] bytes = listener.Receive( ref groupEp);
                receivedCommand = Encoding.ASCII.GetString(bytes,0,bytes.Length);
                Console.WriteLine("Received command: " + receivedCommand + " from " + groupEp.Address);

                //Send matching response
                responseEp = new IPEndPoint(groupEp.Address, ListenPort);
                if (receivedCommand == "U" || receivedCommand ==  "u")
                {
                    using (StreamReader sr = new StreamReader ("/proc/uptime"))
                    {
                        String line = sr.ReadToEnd();
                        Console.WriteLine("Sending uptime: " + line);

                        byte[] sendbuf = Encoding.ASCII.GetBytes(line);
                        s.SendTo(sendbuf, responseEp);
                    }
                }
                else if(receivedCommand == "L" || receivedCommand ==  "l")
                {
                    using (StreamReader sr = new StreamReader ("/proc/loadavg"))
                    {
                        String line = sr.ReadToEnd();
                        Console.WriteLine("Sending load average: " + line);

                        byte[] sendbuf = Encoding.ASCII.GetBytes(line);
                        s.SendTo(sendbuf, responseEp);
                    }
                }
                else
                {
                    Console.WriteLine("Command " + receivedCommand + " not found\n");
                    byte[] sendbuf = Encoding.ASCII.GetBytes("Input not recognized, please try again!");
                    s.SendTo(sendbuf, responseEp);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }
开发者ID:BjornNorgaard,项目名称:I4IKN,代码行数:60,代码来源:ListenerCode.cs

示例10: StartListener

 private static void StartListener()
 {
     bool done = false;
     IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
     UdpClient listener = new UdpClient(groupEP);
     Log.Notice("Listener", "Waiting for broadcast");
     try
     {
         while (!done)
         {
             byte[] bytes = listener.Receive(ref groupEP);
             Log.Info("Listener", "Client " + groupEP.ToString() + " is trying to connect");
             listener.Connect(groupEP);
             Log.Succes("Listener", "Listener connected to client " + groupEP.ToString());
             done = true;
             //TODO - rest of district server connecting
         }
     }
     catch (Exception e)
     {
         FrameWork.Logger.Log.Error("Listener", e.ToString());
     }
     finally
     {
         listener.Close();
     }
 }
开发者ID:harleyknd1,项目名称:rAPB,代码行数:27,代码来源:Listener.cs

示例11: procComm

    void procComm()
    {
        port = getPort();
        string ipadr = getIpadr ();

        client = new UdpClient ();

        // send
        string sendstr = IFmsg.text + System.Environment.NewLine;
        byte[] data = ASCIIEncoding.ASCII.GetBytes (sendstr);
        client.Send (data, data.Length, ipadr, port);

        // receive
        client.Client.ReceiveTimeout = 2000; // msec
        IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0);
        lastRcvd = "";
        try {
            data = client.Receive (ref remoteIP);
            if (data.Length > 0) {
                string text = Encoding.ASCII.GetString (data);
                lastRcvd = text;
            }
        } catch (Exception err) {
        }

        client.Close ();
    }
开发者ID:yasokada,项目名称:unity-150830-udpSender,代码行数:27,代码来源:SendButtonScript.cs

示例12: ThreadFuncReceive

 static void ThreadFuncReceive()
 {
     try
     {
         while (true)
         {
             //подключение к локальному хосту
             UdpClient uClient = new UdpClient(LocalPort);
             IPEndPoint ipEnd = null;
             //получание дейтаграммы
             byte[] responce = uClient.Receive(ref ipEnd);
             //преобразование в строку
             string strResult = Encoding.Unicode.GetString(responce);
             Console.ForegroundColor = ConsoleColor.Green;
             //вывод на экран
             Console.WriteLine(strResult);
             Console.ForegroundColor = ConsoleColor.Red;
             uClient.Close();
         }
     }
     catch (SocketException sockEx)
     {
         Console.WriteLine("Ошибка сокета: " + sockEx.Message);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Ошибка : " + ex.Message);
     }
 }
开发者ID:xs2ranjeet,项目名称:13ns9-1spr,代码行数:29,代码来源:Program.cs

示例13: ReceiveData

	private  void ReceiveData()
	{
		client = new UdpClient(8000);
		while (running)
		{			
			try
			{
				IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
				byte[] data = client.Receive(ref anyIP);				
				
				string text = Encoding.UTF8.GetString(data);
				Debug.Log("Input "+text);
				string[] info = text.Split(':');
				
				inputText = text;
				
				if(info[0].Equals("speed")){
					speed= info[1];
				}
				if(info[0].Equals("turn")){
					axis= info[1];
				}
				
				
			}
			catch (Exception err)
			{
				running =false;
				print(err.ToString());
			}
		}
	}
开发者ID:tattoxcm,项目名称:VRBike,代码行数:32,代码来源:NetworkScript.cs

示例14: ReceiveData

	private void ReceiveData(){

		client = new UdpClient(port); //Binds udp client to random port
		while (true)
		{

			try
			{
				
				IPEndPoint IPEndPoint = new IPEndPoint(IPAddress.Any, 0);
				byte[] data = client.Receive(ref IPEndPoint);

				string text = Encoding.UTF8.GetString(data);

				if(log){
					Debug.Log(text);
				}

				lock(receivedUDPPackets){
					receivedUDPPackets.Add(text);
				}
			}
			catch (Exception err)
			{
				print(err.ToString());
			}
		}
	}
开发者ID:Urauth,项目名称:Finnish-Game-Jam-2016,代码行数:28,代码来源:UDPReceive.cs

示例15: Listen

	private void Listen()
	{
		System.Random myRandom = new System.Random();
		udpClient = new UdpClient(7272, AddressFamily.InterNetwork);

		var endPoint = default(IPEndPoint);

		byte[] bytes;

		while (m_shouldRun)
		{
			try
			{
				bytes = udpClient.Receive(ref endPoint);
				if (bytes == null || bytes.Length == 0)
					break;

				int offset = 0;
				lock (m_threadLock)
				{
					m_head = FromOculusToUnity(Vector3FromBytes(bytes, ref offset));
					m_rHand = FromOculusToUnity(Vector3FromBytes(bytes, ref offset));
					//m_rHandRotation = Vector4FromBytes(bytes, ref offset);
					m_lHand = FromOculusToUnity(Vector3FromBytes(bytes, ref offset));
					//m_lHandRotation = Vector4FromBytes(bytes, ref offset);
					m_rightClosed = BoolFromBytes(bytes, ref offset);
				}
			} catch (ThreadInterruptedException)
			{
				// Empty on purpose
			}
		}
	}
开发者ID:patricio272,项目名称:VRHackZurich,代码行数:33,代码来源:PositionProvider.cs


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