0

我有一个用 C++ 编写的服务器和一个用 C# 编写的客户端。客户端将其数据包发送到服务器,服务器接收它,然后将其发回。不幸的是,除了服务器发回消息外,一切正常。这是简单的代码:

// 服务器

    if ((recv_len = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *) &si_sender, &si_senderSize)) == -1)
    {
        die("recvfrom()", s);
    }

    //print details of the client/peer and the data received
    printf("Received packet from %s:%d\n", inet_ntoa(si_sender.sin_addr), ntohs(si_sender.sin_port));

    std::cout << "Data: " << buf << std::endl;

    //now reply the client with the same data information

    if (sendto(s, buf, sizeof(buf), 0, (struct sockaddr*) &si_sender, si_senderSize) == -1)
    {
        die("sendto()", s);
    }

 //cleanup here

//客户

    private void btnSearch_Click(object sender, EventArgs e)
    {
        bool found = false;
        byte[] text_to_send = Encoding.ASCII.GetBytes("networkinfo");
        client.Send(text_to_send, text_to_send.Length);

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

        while (!found)
        {
            if (client.Available > 0)
            {
                byte[] responseBuffer = client.Receive(ref serverResponse);
                string response = Encoding.ASCII.GetString(responseBuffer);
                writeIPAddress(serverResponse.Address.ToString(), serverResponse.Port.ToString());
                found = true;
            }
        }

服务器在 sendto() 函数上没有失败,但是客户端中的 while 循环永远轮询,因为它没有检测到要在网络上接收的信息,但是 sendto() 函数没有返回错误?

关于网络数据在哪里的任何想法?

4

1 回答 1

0

Ok, i figured it out finally and I want to post the resolution to the problem so other people won't have this headache.

The problem was broadcasting a UDP packet with UDPClient. You CANNOT receive with the same UDPClient object after you broadcast a packet (using ipaddress.broadcast or "255.255.255.255"). The solution I ran into was to immediately close this object, open another one on the same port, then use that new object to receive the response.

//setup broadcast client
broadcastClient = new UdpClient(5454);
broadcastAddress = new IPEndPoint(IPAddress.Broadcast, 8888);
broadcastClient.Connect(broadcastAddress);

//send and immediately close
byte[] text_to_send = Encoding.ASCII.GetBytes("networkinfo");
broadcastClient.Send(text_to_send, text_to_send.Length);
broadcastClient.Close();

//open up new client to receive
UdpClient receivingClient = new UdpClient(5454);
IPEndPoint serverResponse = new IPEndPoint(IPAddress.Any, 0);
byte[] message = receivingClient.Receive(ref serverResponse);
string messageReceived = Encoding.ASCII.GetString(message);

Debug.WriteLine(messageReceived);

I did not see anything about this quirk (problem?) on MSDN, so I'm not sure if this is a bug or it is as intended and just not documented.

于 2013-05-24T21:36:20.667 回答