QTcpSocket inside a QThread

by darthspawn on March 12th, 2010
No notes
Syntax: C++
Show lines - Hide lines - Show in textbox - Download
#include "threadsocket.h"
 
ThreadSocket::ThreadSocket(QString& iqstr_Address, int iint_Port, QObject* parent)
	:QThread(parent), mqstr_Address(iqstr_Address), mint_Port(iint_Port)
{
	i = 0;
	mboo_Connected = false;
}
 
ThreadSocket::~ThreadSocket()
{
	mpqtcp_Socket->close();
	delete mpqtcp_Socket;
}
 
void ThreadSocket::run()
{
	mpqtcp_Socket = new QTcpSocket(this);
	connect (mpqtcp_Socket, SIGNAL (connected()), SLOT(SocketConnected()) );
	//connect (mpqtcp_Socket, SIGNAL (connectionClosed()), SLOT(SocketClosed()), Qt::DirectConnection );
	connect (mpqtcp_Socket, SIGNAL (disconnected()), SLOT(SocketClosed()));
 
	connect (mpqtcp_Socket, SIGNAL (readyRead()), SLOT(SocketAnswer()), Qt::DirectConnection);
	connect (mpqtcp_Socket, SIGNAL (error(int)), SLOT(SocketError(int)) );
 
	mpqtcp_Socket->connectToHost (mqstr_Address, mint_Port);
	exec();
}
 
void ThreadSocket::SendUpdate(QString& iqstr_SendLine, int iint_Size)
{
	qint64 lqint_Ret;
	while (mboo_Connected == false) {
		msleep(100);
	}
	lqint_Ret = mpqtcp_Socket->write(iqstr_SendLine.toStdString().c_str(), iint_Size);
 
	if (mpqtcp_Socket->waitForBytesWritten(1000)) {
		// aspetta la fine dell'invio stringa
	}
}
 
void ThreadSocket::SocketConnected()
{
	mboo_Connected = true;
}
 
void ThreadSocket::SocketAnswer()
{
	qint64 lqint_Length;
 
	if (i == 0) {
		mqtime_Time.start();
	}
 
	char buffer[1024];
	while (mpqtcp_Socket->canReadLine()) {
 
		lqint_Length = mpqtcp_Socket->readLine(buffer, sizeof(buffer));
		if (lqint_Length != -1) {
			emit Sign_RecMsg(buffer, i);
		}
		strcpy(buffer, "");
	}
}
 
void ThreadSocket::SocketError(int iint_Error)
{
	int c = iint_Error;
}
 
void ThreadSocket::SocketClosed()
{
 
}
 
void ThreadSocket::Disconnect()
{
	mpqtcp_Socket->disconnectFromHost();
	mpqtcp_Socket->waitForDisconnected();
}
 

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS