Hello there!
I just got into the Network module of sfml. i wanted to create a small game so i used UdpSocket.
Sadly i havent been able to send anything properly and after some Investigation i noticed my ip address is set to 0.0.0.0 after i use .send(). In this case i use , just to test it, the same ip address for both Client and Server. Heres the Code:
#include <iostream>
#include <SFML\Graphics.hpp>
#include <SFML\Network.hpp>
using namespace sf;
int main()
{
UdpSocket socket;
IpAddress ip= IpAddress::getLocalAddress();
Packet packet;
unsigned short port = 1234;
RectangleShape player1;
RectangleShape player2;
char sc;
Vector2f player2pos;
player1.setSize(Vector2f(20, 20));
player2.setSize(Vector2f(20, 20));
player1.setFillColor(Color::Blue);
player2.setFillColor(Color::Red);
std::cout << "[s] server, [c]client" << std::endl;
std::cin >> sc;
if (sc == 'c')
{
std::cout << "Server ip address" << std::endl;
//std::cin >> ip;
socket.bind(1235);
}
if (sc == 's')
{
socket.bind(1234);
}
bool update = false;
socket.setBlocking(false);
RenderWindow window(VideoMode(800, 600), "Window");
while (window.isOpen())
{
if (sc == 'c')
{
packet << player1.getPosition().x << player1.getPosition().y;
if (socket.send(packet, ip, 1234))
std::cout << "client sent data to " << ip.toString() << std::endl;
socket.receive(packet, ip, port);
packet >> player2pos.x >> player2pos.y;
}
if (sc == 's')
{
if (socket.receive(packet, ip, port))
std::cout << "recieved data from " << ip.toString() << std::endl;
packet >> player2pos.x >> player2pos.y;
packet << player1.getPosition().x << player1.getPosition().y;
socket.send(packet, ip, 1235);
}
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
else if (event.type == Event::GainedFocus)
{
update = true;
}
else if (event.type == Event::LostFocus)
{
update = false;
}
}
if (update)
{
if (Keyboard::isKeyPressed(Keyboard::A))
player1.move(-1.f, 0.f);
else if (Keyboard::isKeyPressed(Keyboard::D))
player1.move(1.f, 0.f);
else if (Keyboard::isKeyPressed(Keyboard::S))
player1.move(0.f, 1.f);
else if (Keyboard::isKeyPressed(Keyboard::W))
player1.move(0.f, -1.f);
}
player2.setPosition(player2pos);
window.clear();
window.draw(player1);
window.draw(player2);
window.display();
}
return 0;
}