Quint16 zero crash
-
I'm reading in a block size for network code, using a quint16 to store the block size. I start the blockSize off as 0, and it's read in when the readMessage() slot is called from the socket's readyRead() signal. The program instantly crashes as soon as readMessage() is called, before the first line even runs. However, if I initialize blockSize as 1 instead of 0, there is no crash at all. The blockSize is never read in if I do this, though, so there are problems. This is an incredibly stupid bug and I don't know what the problem is.
@
class cPlayer
{friend class MainServer;
private:
int id;
QTcpSocket* socket;
quint16 blockSize;
public:
cPlayer() { blockSize = 0; }
};
@Here's the code where the connections are setup. The message that is sent goes through, the client responds, and then the server crashes. The first line of readMessage is (qDebug() << "Message Received") and it doesn't happen.
@
void MainServer::handleNewConnection()
{
while(server->hasPendingConnections()) {
cPlayer* newPlayer = new cPlayer;
newPlayer->init();
newPlayer->id = numPlayers++;
newPlayer->socket = server->nextPendingConnection();
connect(newPlayer->socket, SIGNAL(disconnected()), this, SLOT(handleDisconnection()));
QSignalMapper* sMap = new QSignalMapper(this);
sMap->setMapping(newPlayer->socket, newPlayer->id);
connect(newPlayer->socket, SIGNAL(readyRead()), sMap, SLOT(map()));
connect(sMap, SIGNAL(mapped(int)), this, SLOT(readMessage(int)));
playerList.append(newPlayer);
appendPlainText(QString("[%1]%2 connected - ID %3\n").arg(QTime::currentTime().toString()).arg(newPlayer->socket->peerAddress().toString()).arg(numPlayers-1));
sendMessage(newPlayer->id, 0);
}
}
@ -
Could you post a bit more code ? We don't know how sendMessage works nor readMessage and there might lie your problem.
On an unrelated note, one thing that you could avoid is recreating sMap each time, you don't need one mapper per connection.
-
Here is the sendMessage code:
@
void MainServer::readMessage(int id)
{
appendPlainText("This line is never being hit");
cPlayer* Player = playerAt(id);
if(!Player)
return;
QDataStream in(Player->socket);
in.setVersion(QDataStream::Qt_4_8);
if(Player->blockSize == 0) {
if(Player->socket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> Player->blockSize;
appendPlainText(QString("Block Size:%1").arg(Player->blockSize));
}
if(Player->socket->bytesAvailable() < (quint16)Player->blockSize)
return;
quint16 msgid;
in >> msgid;
appendPlainText(QString("Received Message %1\n").arg(msgid));
switch(msgid) {
case 0:
sendMessage(id, 1);
break;
default:
Player->blockSize = 0;
}
}
@