PDA

View Full Version : TCP Connection



JS27
16th October 2015, 12:02
Hey guys i have a small question.

I would like to connect with several servers by using one thread with different
sockets. It works for one socket but doesnt connect with the other server.

TCP: is the name of the thread. :p



...
header
...

QTcpSocket *socket[10];
...
...
source
...

void TCP::run()
{
initSocket();
}

void TCP::initSocket()
{
for(int i=0;i<2;i++)
{
socket[i] = new QTcpSocket();

connect(socket[i], SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket[i], SIGNAL(connected()),this, SLOT(connected()), Qt::DirectConnection);
connect(socket[i], SIGNAL(disconnected()),this, SLOT(stopConnection()), Qt::DirectConnection);
connect(socket[i], SIGNAL(bytesWritten(qint64)),this, SLOT(bytesWritten(qint64)));

startConnection(i);
}
exec();
}


void TCP::startConnection(int conNUM)
{
QHostAddress addr(address[conNUM]);
socket[conNUM]->connectToHost(addr, port[conNUM]);
}

.....

Thanks

Lesiok
16th October 2015, 12:21
How You recognize in slot the signal sender ?

JS27
16th October 2015, 12:34
void TCP::connected()
{
QObject* obj = sender();
if( obj == socket[0] )
{
qDebug()<<address[0]<<endl;
}

if( obj == socket[1] )
{
qDebug()<<address[1]<<endl;
}

..
}


but he jumps every time to obj == socket[1].

anda_skoa
16th October 2015, 14:26
My suggestion would be to create a "connection" class that has all the slots and create one for each connection.
Each object would get the host address in its constructor, creates the socket, connects the socket, and starts its connection.

No need for Qt::DirectConnection (both socket and connection object live in the TCP thread), no need for if/else in the slots

Cheers,
_