Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Cannot read from Packet.  (Read 2705 times)

0 Members and 1 Guest are viewing this topic.

Martin Lefevre

  • Newbie
  • *
  • Posts: 6
    • View Profile
Cannot read from Packet.
« on: April 02, 2020, 07:06:09 pm »
Hi,

While reading the tutorial about packets, I tried to do my own project to test it. So, I made a peer-to-peer connection between two computers (it works! ^^), and I sent a packet from one to the other... The problem is when I try to read from the packet: the >> operator always returns false.
Here is the code:

On the sender's side:

#include <sfml/network.hpp>

sf::UdpSocket UdpS;

namespace Contact
{
         sf::IpAddress Ip;
        unsigned short Port;
};

int main() {
        UdpS.setBlocking(false);

        //Establishes P2P connection,
       //and finds the other contact's IP and port.
       //Also binds UdpS.
      //Returns true here.
        if (!Connect()) {
                std::cout << "Connection error." << std::endl;
                return 1;
        }
        std::cout << "Connected." << std::endl;

        sf::Uint16 u = 5;
        sf::Packet pack; pack << u;
        if (UdpS.send(pack, Contact::Ip, Contact::Port) != sf::Socket::Done) {
                std::cout << "Failure." << std::endl;
        }
        std::cout << "Sent" << std::endl; //Sent is printed, thus the packet is sent correctly.
}



And on the recipient's side:

#include <sfml/network.hpp>

sf::UdpSocket UdpS;

namespace Contact
{
         sf::IpAddress Ip;
        unsigned short Port;
};

int main() {
        UdpS.setBlocking(false);
        //Establishes P2P connection,
       //and finds the other contact's IP and port.
       //Also binds UdpS.
      //Returns true here.
        if (!Connect()) {
                std::cout << "Connection error." << std::endl;
                return 1;
        }
        std::cout << "Connected.   " << std::endl;

        UdpS.setBlocking(true);
        sf::Packet pack;
        if (UdpS.receive(pack, Contact::Ip, Contact::Port) != sf::Socket::Done) { return 1; }
       
        sf::Uint16 i;
        if (!(pack >> i)) { std::cout << "Reading failed." << std::endl; return 1; } //Reading failed is printed.
       
}
« Last Edit: April 02, 2020, 07:10:49 pm by Martin Lefevre »

Martin Lefevre

  • Newbie
  • *
  • Posts: 6
    • View Profile
Re: Cannot read from Packet.
« Reply #1 on: April 03, 2020, 03:14:51 pm »
Ok, I found the problem: my Connect function sends bytes of data to the other peer, to establish the connection. But if I don't call receive to "clean" the port after that, when I will call receive to collect useful data (such as this packet), I'll collect the random byte instead, thus causing issues such as this one.

 

anything