Udp客户端绑定

本文关键字:绑定 客户端 Udp | 更新日期: 2023-09-27 17:49:22

我有UDP客户端聊天,它向服务器发送消息并获得响应。我有两个线程,一个用于发送消息,一个用于接收消息。我得到了ReceiveFrom()方法的异常:"你必须在执行此操作之前调用Bind方法"。但这是客户端,我不想绑定任何东西。例如,这个客户端工作得很好:

    byte[] data = new byte[30];
    string input, stringData;
    IPEndPoint servIPEP = new IPEndPoint(
            IPAddress.Parse("127.0.0.1"), 9050);
    EndPoint servEP = (EndPoint)servIPEP;
    Socket client = new Socket(AddressFamily.InterNetwork,
            SocketType.Dgram, ProtocolType.Udp);
    string welcome = "Hello, are you there?";
    data = Encoding.ASCII.GetBytes(welcome);
    client.SendTo(data, data.Length, SocketFlags.None, servEP);
    data = new byte[30];
    int recv = client.ReceiveFrom(data, ref servEP);    //works fine!

没有接收绑定。但是当我创建两个线程时抛出错误:

 public ChatClient()
        {
            clientSock = new Socket(AddressFamily.InterNetwork, 
                               SocketType.Dgram, ProtocolType.Udp);
            servIPEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 32000);
            servEP = (EndPoint)servIPEP;
        }
         public void ReceiveThread()
        {
            Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
            receiveThread.Start();
        }
        public void ReceiveData()
        {
           while(true){
                clientSock.ReceiveFrom(buf, ref servEP); //Here I get ERROR
                string msg = Encoding.ASCII.GetString(buf).Trim();
                Console.WriteLine("New message: {0}",msg);
                }
        }
        public void SendThread()
        { 
            Thread sendThread = new Thread(new ThreadStart(SendData));
            sendThread.Start();
        }
        public void SendData()
        {
            while (true)
            {
                Console.WriteLine("Enter message to send: ");
                string msg = Console.ReadLine();
                buf = Encoding.UTF8.GetBytes(msg);
                clientSock.SendTo(buf, servEP);
            }
        }
    }

    static void Main(string[] args)
    {
        ChatClient client = new ChatClient();
        client.SendThread();
        client.ReceiveThread();
    }
}

感谢您的宝贵时间。

Udp客户端绑定

显然SendTo()做了隐式绑定,而ReceiveFrom()没有。

在没有事先绑定的情况下开始接收没有多大意义,至少要设置您正在接收的端口号。否则你怎么能指望得到数据呢?