0

I am making a game, I have 2 clients and a server. When I move in the game, I send data to server (1-left,2-up,3-right,4-down). The server sends forward to the other client.

Here is the server :

#include <iostream>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
using namespace std;

void recAndGive(sf::SocketTCP fromSock, sf::SocketTCP toSock)
{
   sf::Packet Packet;
   if(fromSock.Receive(Packet) == sf::Socket::Done)
   {
       toSock.Send(Packet);
   }

}

int main()
{
   cout << "Server is running. [192.168.1.100] [4567]" << endl << endl;
   sf::IPAddress Client1_ip;
   sf::IPAddress Client2_ip;

   sf::SocketTCP Client1;
   sf::SocketTCP Client2;

   sf::SocketTCP Listener;

   if(!Listener.Listen(4567))
       return 1;

   cout << "Server is listenig to port 4567, waiting for connections..." << endl;

   //waiting for client1
   Listener.Accept(Client1,&Client1_ip);
   cout << "Client connected : " << Client1_ip << endl;

   //waiting for client2
   Listener.Accept(Client2,&Client2_ip);
   cout << "Client connected : " << Client2_ip << endl;

   while(true)
   {
       recAndGive(Client1,Client2);
       recAndGive(Client2,Client1);
   }


   return 0;
}

It doesnt work good. The server runs on my PC, the clients run on my laptop. If I start two clients and I move with one, I receive wrong packets in wrong order in each client (?).

If I remove this line:

recAndGive(Client2,Client1);

then I start two clients, and I move with the first one then I receive perfect data on the second client. What is the problem? Please help me :)

cylon
  • 735
  • 1
  • 11
  • 26

1 Answers1

0

http://sfml-dev.org/tutorials/2.1/network-socket.php

You should not have any problem if you use this guide.

Only problem I had was, when I add like packet << coorX << coorY, and open that packet like packet >> p2CoorX >> p2CoorY, I had a big issue, problem was, packet was not cleaning at all. so it puts coorX and coorY to packet, and it does it again and again... packet is getting really big and while its getting bigger, the receiving part (packet >> p2CoorX >> p2CoorY) reads only the first two variables.

That was my problem but I fixed it with using packet.clear();