none
C#中用UdpClient怎么抓不同IP的包? RRS feed

  • 问题

  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class l_Server
        {
            static byte[] buffer = new byte[8192];
            static AsyncCallback _callback_onReceive = new AsyncCallback(callback_onReceive);
    
            static void Main(string[] args)
            {
                UdpState state = new UdpState();
                state.client.BeginReceive(_callback_onReceive, state);
    
                while (true)
                {
                    string str = Console.ReadLine();
                    byte[] b = Encoding.UTF8.GetBytes(str);
                }
            }
    
            static void callback_onReceive(IAsyncResult result)
            {
                UdpState state = (UdpState)(result.AsyncState);
    
                buffer = state.client.EndReceive(result, ref state.endpoint);
                Console.WriteLine("Client[" + state.endpoint.Address + "]: " + Encoding.UTF8.GetString(buffer));
    
                byte[] str = Encoding.UTF8.GetBytes("Received.");
                state.client.Connect(state.endpoint);
                state.client.SendAsync(str, str.Length);
    
                state.client.BeginReceive(_callback_onReceive, state);
            }
        }
    
        class UdpState
        {
            public UdpClient client;
            public IPEndPoint endpoint;
    
            public UdpState()
            {
                this.endpoint = new IPEndPoint(IPAddress.Any, 54464);
                this.client = new UdpClient(endpoint);
            }
        }
    }
    


    以上就是我的代码,在实际运行的时候无法接收到第二个IP发来的包( ´_ゝ`)

    感觉是Connect导致的,但是没有找到Disconnect方法

    2014年7月11日 4:19

答案

  • 你好:

    请问第二个IP的端口也是54464吗?据你的代码来看你的UDP类只接收54464端口发送过来的数据。如果你把端口号改为0,就可以接受任何端口了。

    最好将本地监听的端口和远程的客户端端口区分开来,你的代码里面本地监听的端口是54464:

    this.endpoint = new IPEndPoint(IPAddress.Any, 54464);
    this.client = new UdpClient(endpoint);

    然后接收的远程的端口也是同样的IPEndPoint:
    buffer = state.client.EndReceive(result, ref state.endpoint);


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年7月14日 6:17
    版主