Try this:
#include "mytcpserver.h"
MyTcpServer::MyTcpServer(QObject *parent) :
QObject(parent)
{
server = new QTcpServer(this);
// whenever a user connects, it will emit signal
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if(!server->listen(QHostAddress("127.0.0.1"), 3333))
{
qDebug() << "Server could not start";
}
else
{
qDebug() << "Server started!";
}
}
void MyTcpServer::on_readyRead()
{
QTcpSocket * senderSocket = dynamic_cast<QTcpSocket*>(sender());
if(senderSocket)
{
qDebug() << "reading data";
qDebug() << senderSocket->readAll();
}
}
void MyTcpServer::newConnection()
{
// need to grab the socket
QTcpSocket * newSocket = server->nextPendingConnection();
if(newSocket)
{
connect(newSocket ,SIGNAL(readyRead()),this,SLOT(on_readyRead()));
//Additionnal auto clean-up without keeping track of the pointer
connect(newSocket ,SIGNAL(disconnected()),newSocket ,SLOT(deleteLater()));
}
}
(When you declare this:
QTcpSocket *sok=new QTcpSocket();
This creates a local QTcpSocket pointer, which hides the sok
member of your class.
Also, you create a QTcpSocket with new, and lose it at the next line (memory leak)
sok = server->nextPendingConnection();
So the sok
member variable of your class is never used with an incoming connection.
You are using a member variable called sok
in MyTcpServer
class and a local variable sok
in MyTcpServer::on_readyRead
, this is a bad idea.
Proper use of QTcpServer would be:
- Store incoming connections in a member variable pointer
- Connect its readyRead signal