PDA

View Full Version : QTcpSocket Help



minotaurds
20th October 2011, 12:18
Hi,
i am trying to build a Console Socket Program with the following code :


#include <QtCore/QCoreApplication>
#include "client.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Client client;
return a.exec();
}
Client::~Client()
{

}

Client::Client()

{
QTcpSocket *client = new QTcpSocket(this);

Establish(client);
}

void Client::Establish(QTcpSocket *client)
{
quint16 port=18999;
client->connectToHost(QHostAddress::LocalHost , port, QIODevice::ReadWrite);

if (!client->waitForConnected()){

for(int j=0;j<10;j++)
qDebug("Error");

exit(11);
}
getData(client);
}

void Client::getData(QTcpSocket *client)
{

client->waitForReadyRead();
QString line;
if (client->canReadLine()) {
line = client->readLine();
}
else
qDebug("Error");

qDebug()<<line;
if(!client->waitForConnected())
stop(client);
else
Establish(client);
}
void Client::stop(QTcpSocket *client)
{
client->flush();
client->waitForBytesWritten();

client->close();
client->disconnectFromHost();
client->waitForDisconnected();

}

Server:

#include <QtCore/QCoreApplication>
#include "server.h"
#include <QTcpServer>
#include <QTcpSocket>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MultiClientServer serve;
return a.exec();
}

MultiClientServer::MultiClientServer()
{
start();
connect(this, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));

}

void MultiClientServer::handleNewConnection()
{ qDebug("Somethin");
client = nextPendingConnection();
connect(client, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));

sendHello(client);
}

void MultiClientServer::clientDisconnected()
{
client->deleteLater();
}

void MultiClientServer::sendHello(QTcpSocket *client)
{
if (!client)
return;

client->write("1");

}

MultiClientServer::~MultiClientServer()
{
stop();
}
//The stop function closes the connections. The server will not listen anymore. Any client trying to connect will time out. Use the QTcpServer::close() function to stop listening.

void MultiClientServer::stop()
{
close();
}

//The start function makes the server listen on a certain hostname and a certain port. In this case the hostname and port are not variable, the server will listen on localhost on the port 1234. You can of course create a settings dialog where you can change these settings.


void MultiClientServer::start()
{
qDebug("Server Started");
listen(QHostAddress::LocalHost, 18999);
}




Someone Please Help me !


I want to transfer Integer Values but the write only allows QString/Character!!

Secondly I have some error cause the client only recieves data once.

By changing the localHost with the IP address should send the data to that IP address right?

Suggestions to convert this into GUI



OKAY I FOUND OUT THAT EVERY TIME MY SERVER SENDS THE MESSAGE IT DISCONNECTS WITH THE CLIENT!