I am having a problem sending messages with non-blocking UDP sockets. I have reduced the problem to two minimal pieces of code. The following code works:
#include<SFML\Graphics.hpp>
#include<SFML\Network.hpp>
#include<string>
#include<iostream>
using namespace std;
//Variables
sf::RenderWindow window;
sf::UdpSocket socket;
sf::Packet packet;
sf::IpAddress address;
unsigned short port = 3500;
int message = 0;
int main()
{
window.clear();
window.display();
//Setup
string line;
socket.bind(3500);
cout << "Enter IP: " << endl;
cin >> line;
address = sf::IpAddress(line);
//Note - non blocking
socket.setBlocking(false);
while (!sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.clear();
window.display();
packet.clear();
packet << 100;
socket.send(packet, address, port);
socket.receive(packet, address, port);
while (packet.getDataSize() > 0)
{
int message;
packet >> message;
cout << message << endl;
}
}
}
But the following does not:
#include<SFML\Graphics.hpp>
#include<SFML\Network.hpp>
#include<string>
#include<iostream>
using namespace std;
//Variables
sf::RenderWindow window;
sf::UdpSocket socket;
sf::Packet packet;
sf::IpAddress address;
unsigned short port = 3500;
int message = 0;
int main()
{
window.clear();
window.display();
//Setup
string line;
socket.bind(3500);
cout << "Enter IP: " << endl;
cin >> line;
address = sf::IpAddress(line);
//Note - non blocking
socket.setBlocking(false);
while (!sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.clear();
window.display();
packet.clear();
packet << 100;
socket.send(packet, address, port);
socket.receive(packet, address, port);
while (packet.getDataSize() > 0)
{
int message;
packet >> message;
cout << message << endl;
socket.receive(packet, address, port);
}
}
}
The only difference between the two pieces of code is the extra socket.receive() call. Why is this causing the second piece of code to break down?