Hello, I made a simple chat using tutorials on SFML-page. I created separate thread to receive data. Sending from client to server is not possible, but if I want to send from server to client this is possible only first time , next times client receive old message (e.g from server i send "Hello", client receive this message , send next time but another text e.g "Hello123" , and client show "Hello" again .
Here is code
client :
#include "stdafx.h"
#include <SFML/Network.hpp>
#include <iostream>
#include <cstdlib>
using namespace std;
sf::TcpSocket socket ;
sf::Mutex globalMutex;
void receive_and_show_data ()
{
static string oldMsg;
while (true)
{
string msg;
sf::Packet pakiet_receive;
socket.setBlocking (false);
socket.receive(pakiet_receive);
if(pakiet_receive >> msg)
{
if(!msg.empty())
{
std::cout << msg << std::endl;
oldMsg = msg;
}
}
}
}
int main(int argc, char* argv[])
{
cout << "Client" << endl ;
char data_send [100];
bool quit = true ;
cout << "Write a IP adress : " << endl ;
string adres_ip_string ;
cin >> adres_ip_string ;
sf::Packet pakiet_send ;
sf::Socket::Status status = socket.connect (adres_ip_string,5000);
if (status != sf::Socket::Done )
{
cout << "Nie mozna polaczyc " << endl ;
}
else if (status == sf::Socket::Done)
{
cout << "Connected" << endl ;
quit = false ;
sf::Thread receiveThread (&receive_and_show_data);
receiveThread.launch () ;
while (quit == false)
{
cin.getline(data_send,100);
pakiet_send << data_send ;
globalMutex.lock();
if (socket.send (pakiet_send) != sf::Socket::Done )
{
cout << "Nie udalo sie wyslac danych " << endl ;
}
globalMutex.unlock();
}
}
return 0;
}
Server :
#include "stdafx.h"
#include <SFML/Network.hpp>
#include <string>
#include <iostream>
using namespace std ;
const short PORT = 5000 ;
sf::TcpSocket socket;
sf::Mutex globalMutex;
void receive_show_data ()
{
static string oldMsg;
while (true)
{
string msg;
sf::Packet pakiet_receive;
socket.receive(pakiet_receive) ;
if(pakiet_receive >> msg)
{
if(oldMsg != msg)
if(!msg.empty())
{
std::cout << msg << std::endl;
oldMsg = msg;
}
}
}
}
int main(int argc, char* argv[])
{
char data_send[100];
bool running = true ;
sf::TcpListener listener ;
listener.listen (PORT);
sf::Packet pakiet_send ;
if ( listener.accept (socket) == sf::Socket::Done )
{
cout << "Connected with : " << socket.getRemoteAddress() << endl ;
}
sf::Thread receiveThread (&receive_show_data);
receiveThread.launch () ;
while (running)
{
cin.getline(data_send,100);
pakiet_send << data_send ;
if (socket.send (pakiet_send) != sf::Socket::Done )
{
cout << "Nie udalo sie wyslac danych " << endl ;
}
}
return 0;
}
Thanks for possible reply