我有一个用C ++编写的服务器和一个用C#编写的客户端。客户端将其数据包发送到服务器,服务器接收它,然后将其发回。不幸的是,当服务器发回消息时,一切都有效。这是简单的代码:
// SERVER
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
// CLIENT
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()函数没有返回错误?
任何关于网络数据的想法是什么?
答案 0 :(得分:0)
好吧,我终于弄清楚了,我想把这个问题的解决方案发布给其他人,让其他人不会感到头疼。
问题是使用UDPClient广播UDP数据包。在广播数据包后,您无法使用相同的UDPClient对象(使用ipaddress.broadcast或&#34; 255.255.255.255&#34;)。我遇到的解决方案是立即关闭此对象,在同一端口上打开另一个对象,然后使用该新对象接收响应。
//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);
我在MSDN上没有看到关于这个怪癖(问题?)的任何内容,所以我不确定这是一个错误还是它是预期的,只是没有记录。