so im working with chat app using QT and SFML network. and ive been fixing this problem for 2 days T_T
i have a class in client side that runs SFML thread which is running a function to receive data from server:
void ClientManager::receiveMessage()
{
sf::Packet packet;
if ( client.receive(packet) == 0 )
{
qDebug() << "Message received!";
std::string name;
int a;
packet >> a >> name;
qDebug() << QString::fromStdString(name);
qDebug() << a;
}
}
here is how the client connects to server:
void ClientManager::connectToServer()
{
if ( client.connect("192.168.1.101",5000) == 0 )
{
qDebug() << "Connected";
sf::Packet name;
name << Login::getName().toStdString(); // name of the client
if ( client.send(name) == 0 ) // send the name to the server, then the server will send the name to other clients to know who joins the room
{
qDebug() << "Name sent!";
}
}
}
On the server side:
sf::Packet packet;
while(true)
{
if ( selector.wait() )
{
if ( selector.isReady(server) )
{
sf::TcpSocket* newClient = new sf::TcpSocket;
if ( server.accept(*newClient) == 0 )
{
selector.add(*newClient);
clients.push_back(newClient);
if ( newClient->receive(clientPacket) == 0 )
{
int identifier = 0; // for testing
clientPacket << identifier; // for testing
for ( std::vector<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); it++ )
{
if ( newClient != *it ) // dont send to the sender of the packet
{
if ( (*it)->send(clientPacket) == 0 )
{
qDebug() << "Sent";
}
}
}
}
}
}
}
}
heres the flow:in the 2nd snippet, the new client will join the chat room successfully and it will send his/her name to the server
then in the 3rd snippet, the server will send the name of the new client to the other client so they will know who joins the chat room.
in the first snippet, the other client will receive the name of the new client.
heres whats happening when the program is runin the 2nd snippet, a new client joins succesfully ( so no problem in 2nd snippet) and sends his/her name to the server ( no problem again )
in the 3rd snippet, server receives the name of the new client (so no problem again, i extracted the packet's content when i tested the program, it successfully receives the name)
in the first snippet, it receives the packet successfully (so no problem again) so the if statement will be executed, if you can see the
packet >> a >> name;
in the first snippet, i exctracted it to test if the packet's content is the content i expected, but when
qDebug() << QString::fromStdString(name);
qDebug() << a;
is executed, the output is not what i expected.
the output i expect is the name of the client and 0 (int)
but the output is both garbage values.
now im lost, i dont know if the packet is corrupt since im using tcpsocket it is not corrupted, so i dont know now.
EDIT: the server and client side are separate project.