1
Network / The problem of transferring data to clients with a UDP socket
« on: June 17, 2024, 11:44:24 am »
There is a server that creates an array of integers and puts them in a package, and two clients that immediately after connecting receive a package with an array of integers and use it to generate a game map.
The problem is that if both clients are connected to localhost, then they receive the same data, when connected from different devices, clients receive different data.
server.cpp
client.cpp
What could be the reason for this behavior and how can it be fixed?
The problem is that if both clients are connected to localhost, then they receive the same data, when connected from different devices, clients receive different data.
server.cpp
sf::UdpSocket socket;
if (socket.bind(54000) != sf::Socket::Done) {
return -1;
}
std::cout << "Server is listening on port 54000" << std::endl;
const sf::Uint16 side = 10;
sf::Uint16 level[side * side];
for (int i = 0; i < std::size(level); i++) {
int start = 0;
int end = side;
int x = rand() % (end - start + 1) + start;
if (x < 3)
level[i] = 1;
else
level[i] = 0;
}
....
sf::Packet packet;
packet << level[side * side];
socket.send(packet, client1Ip, client1Port);
if (socket.bind(54000) != sf::Socket::Done) {
return -1;
}
std::cout << "Server is listening on port 54000" << std::endl;
const sf::Uint16 side = 10;
sf::Uint16 level[side * side];
for (int i = 0; i < std::size(level); i++) {
int start = 0;
int end = side;
int x = rand() % (end - start + 1) + start;
if (x < 3)
level[i] = 1;
else
level[i] = 0;
}
....
sf::Packet packet;
packet << level[side * side];
socket.send(packet, client1Ip, client1Port);
client.cpp
const sf::Uint16 side = 10;
sf::Packet packet;
if (socket.receive(packet, serverIp, port) != sf::Socket::Done) {
std::cerr << "Error receiving data" << std::endl;
return -1;
}
sf::Uint16 level[side*side];
packet >> level[side*side];
sf::Packet packet;
if (socket.receive(packet, serverIp, port) != sf::Socket::Done) {
std::cerr << "Error receiving data" << std::endl;
return -1;
}
sf::Uint16 level[side*side];
packet >> level[side*side];
What could be the reason for this behavior and how can it be fixed?