PDA

View Full Version : How to create QTCPSocket object with nextPendingConnection?



pratsam
5th August 2015, 10:49
get the error:

> QIODevice::write (QTcpSocket): device not open.
After trying , I think problem is passing parameter server->nextPendingConnection() into object. Can someone has idea how to do it correctly?

My understanding is that object for `socketClient` is not initialised properly.
I'm using Ubuntu with Qt.

I am implementing server using Qt. The server part has two classes based on `QTcpServer` and `QTcpSocket`.
say `Server` and `SocketClient`.
I am creating object of SocketClient in server and for testing purpose I opened telnet session and wants to see that server write "hello" on terminal. But somehow its not working. Can someone please advice me where I am making mistake.


Server::Server(QObject *parent) : QObject(parent)
{
server_obj = new QTcpServer( this );
}

void Server::startServer()
{
connect( server_obj, SIGNAL( newConnection() ), this, SLOT( incomingConnection() ) );
if( !server_obj->listen( QHostAddress::Any, 9999) )
{
qDebug() << " Server failed to get started";
}
else
{
qDebug() << " Server started"; // this is successful
}
}


void Server::incomingConnection()
{
socketforClient = new SockClient( server_obj->nextPendingConnection() );// has a doubt on nextPendingconection?? May be Problem HERE..

//only for testing remove it
socketforClient->writeToClient();
}

Class for Client


* Description: Its a constructor.I have changed default constructor to add QTcpSocket* object in parameter.I used this constructor in void Server::incomingConnection()
*/
SockClient::SockClient(QObject *parent,QTcpSocket* socket ) : QObject(parent)
{
socketClient = new QTcpSocket( socket ); // PROBLEM HERE ?

qDebug() << " we are in constructor of 1st sockclient ";

}



// this is for testing purpose only

void SockClient::writeToClient()
{
socketClient->write(" hello world\r\n");
socketClient->flush();
socketClient->waitForBytesWritten(3000);

}

//header file of SockClient


class SockClient : public QObject
{
Q_OBJECT
public:

explicit SockClient( QObject *parent, QTcpSocket* socket= 0 ); // I have created
void writeToClient(); // This is for testing purpose
~SockClient();
signals:

private slots:
void readClient();

private:
void sendResponsetoMops();

QTcpSocket *socketClient;

quint16 nextBlockSize;

public slots:
};

ChrisW67
5th August 2015, 11:06
QTcpServer::nextPendingConnection() returns an open QTcpSocket connected to the client. Why are you trying to create another one? This other socket you never connect or open...

anda_skoa
5th August 2015, 14:19
And you never use the socket returned by nextPendingConnection(), you are passing it as the parent of SockClient.

Cheers,
_

wojiaoguowei
6th August 2015, 10:20
void Server::incomingConnection()
{
QTcpSocket *newsocket = m_tcpServer->nextPendingConnection();

connect(newsocket,SIGNAL(readyRead()),this,SLOT(re adyRead()));
}