Udp server using Qt, server status reports - qt

I'm trying to make simple Udp communication between two application.
Client sends request to server to start some processing calculations etc. Server response is result of this computations. Server should report about its state.
My code:
onServerRecv method:
void MainWindow::onServerRecv()
{
while(m_udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(m_udpSocket->pendingDatagramSize());
m_udpSocket->readDatagram(datagram.data(),datagram.size(),&m_sender,
&m_senderPort);
QDateTime dt = QDateTime::currentDateTime();
QString sDtString = dt.toString("yyyy-MM-dd HH:mm:ss");
QString sLog = sDtString + ":" + QString::fromUtf8(datagram) + "\n";
m_textEdit->append(sLog);
//process datagram
instructionCall(datagram,m_sender,m_senderPort);
}
}
instructionCall:
void MainWindow::instructionCall(QByteArray instruction, QHostAddress addr,
qint16 senderPort)
{
if(instruction == "start")
{
QByteArray started = "started";
m_udpSocket->writeDatagram(started,m_sender,m_senderPort);
m_status = "bussy";
connect(&m_timer1,SIGNAL(timeout()),this,SLOT(sendStatus()));
m_timer1.start(500);
for(int i = 0; i != std::numeric_limits<int>::max(); i++)
{
}
m_status = "finished data ready";
disconnect(&m_timer1,SIGNAL(timeout()),this,SLOT(sendStatus()));
QByteArray finished = "finished";
m_udpSocket->writeDatagram(finished,m_sender,m_senderPort);
}
}
sendStatus:
void MainWindow::sendStatus()
{
m_udpSocket->writeDatagram(m_status,m_sender,m_senderPort);
}
I hope that it's clear what I want to do. Any suggestions about solutions? Can it be done without threads?

Related

problem with QLocalSocket sending continues data to QLocalServer

I'm trying to send some data from QLocalSocket to QLocalSever in a loop. Sever only gets the first data and not receiving subsequent data, but if I introduce 1 mec delay between each call from the client then the server starts to receive everything. Please check out the below Client & Server code.
client.cpp
#include "client.h"
#include "QDataStream"
#include <QTest>
TestClient::TestClient() : m_socket{new QLocalSocket(this)}{
m_socket->connectToServer("TestServer");
if (m_socket->waitForConnected(1000)) {
qDebug("socket Connected!");
}
connect(m_socket, &QLocalSocket::readyRead, this, &TestClient::onNewData);
}
void TestClient::onNewData() {
qCritical() << "data received from server";
}
void TestClient::sendDataToServer() {
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_10);
QString testString = "test data";
out << quint32(testString.size());
out << testString;
m_socket->write(block);
m_socket->flush();
}
void TestClient::startClient() {
for(int i = 0; i < 5; i++) {
//QTest::qWait(1); //works if I uncomment this line
sendDataToServer();
}
}
server.cpp
#include "server.h"
TestServer::TestServer() : m_server{new QLocalServer(this)} {
QLocalServer::removeServer("TestServer");
if (!m_server->listen("TestServer")) {
qCritical() << "couldn't connect to server";
}
connect(m_server, &QLocalServer::newConnection, this, &TestServer::onNewConnection);
}
void TestServer::onNewConnection() {
m_socket = m_server->nextPendingConnection();
connect(m_socket, &QLocalSocket::readyRead, this,
&TestServer::onNewData);
connect(m_socket, &QLocalSocket::disconnected, m_socket,
&QLocalSocket::deleteLater);
}
void TestServer::onNewData() {
QLocalSocket* client = qobject_cast<QLocalSocket*>(sender());
client->readAll();
qCritical() << "data read by server";
}
from the qt doc, it's stated that
readyRead() is not emitted recursively; if you reenter the event loop
or call waitForReadyRead() inside a slot connected to the readyRead()
signal, the signal will not be reemitted (although waitForReadyRead()
may still return true).
so is this my problem? adding timer is the only solution here?
You can compile this test project -> http://www.filedropper.com/testsocket

Handle multiple Qtcp connections concurrently to show on marble widget

I have an application with qt creator that gets geocoordinate data and shows it on the map.it works fine with just one connection but when it comes to having more than once makes it a riddle.
I want to get data in a loop from several qtcp connections with different addresses and ports then put data in separated lists and after reading the list of each connection geodata add separate layers on a map in different threads which updates every 3 seconds while all of them getting data concurrently from the network packets. suppose I have many different gps receivers to gather data of their location I want to integrate it on the map.
here is my code sample:
1.define list of servers that qtcp client should be connected:
globals.cpp
#define PACKET 50
struct Connects{
static QMap<QString,int> list()
{
QMap<QString,int> m;
m["sender1.com"] = 4456;
m["sender2.com"] = 4457;
m["sender3.com"] = 4458;
return m;
}
static const QMap<QString,int> myMap;
};
QMap<QString, int> const Connects::myMap = list();
2.main window to launch map:
main.cpp
void add_layer(MarbleWidget *mapWidget,MainWindow *window,Client *client,QTimer *timer ){
//get data and append to a list every 3 sec
timer = new QTimer;
QObject::connect(timer,SIGNAL(timeout()),window,SLOT(next_client()));
QObject::connect(client,SIGNAL(Client_Connected()),window,SLOT(online_slot()));
timer->start(3000);
// Add New Layer based on positions in the list
MPaintLayer* layer = new MPaintLayer(mapWidget);
for(int j = 0; j < client->data.count(); ++j){
layer->setPosition(client->data.at(j).Lat,client->data.at(j).Lon);
}
mapWidget->addLayer(layer);
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
// Load Marble
MarbleWidget *mapWidget = new MarbleWidget;
mapWidget->show();
//iterate over connections address and port list
QMapIterator<QString,int> i(Connects::myMap);
while (i.hasNext()) {
i.next();
client = new Client;
client->ConnectToServer(i.key(),i.value());
//make thread pool and create new thread for adding each layer
QThreadPool pool;
QFuture<void> tr;
tr = QtConcurrent::run(&pool,add_layer,mapWidget,this,client,timer);
}
}
void MainWindow::online_slot()
{
//fetch data from the buffer and separate each entity based on size
while (client->GetLanBufferSize() >= PACKET) {
client->ReadData((char*)buffer,PACKET);
double lat,lon;
memcpy(&lat,&buffer[8],sizeof(double));
memcpy(&lon,&buffer[16],sizeof(double));
//put buffer data to target list which is defined in client
Target trg;
client->data.append(trg);
}
//remove has-readed data
for (int var = 0; var < client->data.count(); ++var) {
client->data.removeAt(var);
var--;
}
}
3.declare class for add or update a new layer based on recieved data on the map:
paintlayer.cpp
MPaintLayer::MPaintLayer(MarbleWidget* widget)
{
S_N = QPixmap(":/mode-s.png");
}
bool MPaintLayer::render( GeoPainter *painter,ViewportParams *viewport,
const QString& renderPos, GeoSceneLayer * layer )
{
//throw a tiny png file on map based on retrieved locations
for (int var = 0; var < pos.count(); ++var) {
painter->drawPixmap(pos[var],S_N));
}
return true;
}
void MPaintLayer::setPosition(double lat,double lon)
{
pos.append(GeoDataCoordinates(lat,lon,0,GeoDataCoordinates::Degree));
}
5.define a class for the format of received data:
client.h
class Target
{
public:
Target()
{
Lat = Lon = 0;
}
double Lat,Lon;
GeoDataCoordinates Position;
void update(double lat,double lon)
{
Lat = lat;
Lon = lon;
Position = GeoDataCoordinates(Lon,Lat,0,GeoDataCoordinates::Degree);
}
};
6.declare class for making new qtcp connection and receive data:
client.cpp
Client::Client(QObject *parent) : QObject(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),this, SLOT(on_connected()));
}
void Client::on_connected()
{
connect(socket, SIGNAL(disconnected()),this, SLOT(on_Disconnected()));
socket->setReadBufferSize(12e6);
emit Client_Connected();
}
bool Client::ReadData(char *buffer, int Leanth)
{
socket->read(buffer , Leanth);
return true;
}
int Client::GetLanBufferSize()
{
return socket->bytesAvailable();
}
void Client::on_Disconnected()
{
emit Client_DisConnected();
}
void Client::ConnectToServer(QString Address , int Port)
{
socket->connectToHost(Address, Port);
server = Address;
server_Port = Port;
}
the data format which is received from the senders is location of moving object something like this:
35.51243 51.22478
35.51260 51.22667
35.69270 51.03961
what is the best practice solution? because it shows nothing on the map. when I used hard code, it showed layers equivalent to each connection but reading stream of data is challengeable.
any clue would be appreciated.
You are not using QTcpSocket in its proper way.
In your Client class, you can handle all reading stuff and you won't even need those while loops. Use QIODevice::readyRead() signal and QIODevice::read(char *data, qint64 maxSize) method inside a slot which should read data and parse it.
The problem here is that it's not guaranteed that those data will be received with alignments happening on the sender side. For example, if you send >>>SOME_LENGTHY_DATA<<< from the sender, QTcpSocket may emit readyRead() signal two times and you can read >>>SOME_LENG and THY_DATA<<< in two different calls to your reading slot.
So, you should take care of parsing your data as data is coming in byte by byte.
You are free to buffer the incoming data somewhere in your class or just use the QTcpSocket internal buffer. You should really take care of separating message chunks that are coming in.
Here is an implementation of Client. I use QPointF to store point instead of your Target class because I don't know what it is. You are free to create your own class and append it to Client::data based on parsed lat/lon. I did not test the code but it should work.
I'm not sure if you ever need concurrency with this implementation but you won't need one IMHO.
//Client.h
class Client : public QTcpSocket
{
Q_OBJECT
public:
explicit Client(QObject *parent = nullptr);
private:
QString serverAddress;
int serverPort;
QList<QPointF> data; //you can use your own type, just for test
QByteArray lastLine;
void parseData();
signals:
void Client_Connected();
public slots:
void connectToServer(const QString& address, quint16 port);
void processData();
};
//Client.cpp
#include "client.h"
Client::Client(QObject *parent) : QTcpSocket (parent)
{
// we don't really want Client_Connected signal!
// you can use QTcpSocket::connected signal
connect(this, SIGNAL(connected()),this, SIGNAL(Client_Connected()));
// readyRead will be emitted when there is data in buffer to be read
connect(this, SIGNAL(readyRead()),this, SLOT(processData()));
}
void Client::parseData()
{
QString str(lastLine);
str = str.trimmed();
QStringList parts = str.split(" ",QString::SkipEmptyParts);
if(parts.count()==2){
bool success = true;
double latitude = success ? parts[0].toDouble(&success) : 0;
double longitude = success ? parts[1].toDouble(&success) : 0;
if(success)
data.append(QPointF(longitude,latitude));
}
}
void Client::connectToServer(const QString& address, quint16 port)
{
data.clear();
lastLine.clear();
serverPort = port;
serverAddress = address;
this->connectToHost(address,port);
}
void Client::processData()
{
QByteArray d = this->readAll();
for(int i = 0 ; i < d.count() ; ++i){
if(d.at(i)=='\r')
{
parseData();
lastLine.clear();
}
else
lastLine.append(d.at(i));
}
}

QTcpSocket data arrives late

I am using QTCPSockets to talk to a program I've written in Qt for Raspberry Pi. The same software runs on my Mac (or Windows, whatever). The Pi is running a QTCPServer.
I send JSON data to it and most of the time this goes ok.
But sometimes, the Pi is not responding, the data does not seem to arrive. But then, when I send some more data, that data is not being handled, but the previous Json message is! And this stays like this. All the messages are now off by 1. Sending a new messages, triggers the previous one.
It feels a bit connected to this bugreport: https://bugreports.qt.io/browse/QTBUG-58262
But I'm not sure if it is the same.
I've tried waitForBytesWritten and flush and it seemed to work at first, but later I saw the issue again.
I expect that the TCP buffer on the Pi is not being flushed, but I do now know how to make sure that all data is handled right away.
As asked, here is some sourcecode:
This is the client software:
Client::Client() : tcpSocket(new QTcpSocket(this)), in(tcpSocket)
{
connect(tcpSocket, &QIODevice::readyRead, this, &Client::readData);
connect(tcpSocket, &QTcpSocket::connected, this, &Client::connected);
connect(tcpSocket, &QTcpSocket::stateChanged, this, &Client::onConnectionStateChanged);
void (QAbstractSocket:: *sig)(QAbstractSocket::SocketError) = &QAbstractSocket::error;
connect(tcpSocket, sig, this, &Client::error);
}
void Client::connectTo(QString ip, int port) {
this->ip = ip;
this->port = port;
tcpSocket->connectToHost(ip, port);
}
void Client::reconnect() {
connectTo(ip, port);
}
void Client::disconnect()
{
tcpSocket->disconnectFromHost();
}
void Client::connected()
{
qDebug() << TAG << "connected!";
}
void Client::error(QAbstractSocket::SocketError error)
{
qDebug() << TAG << error;
}
void Client::sendData(const QString& data)
{
bool connected = (tcpSocket->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << "NOT CONNECTED!";
return;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << data;
tcpSocket->write(block);
tcpSocket->flush();
}
void Client::sendData(const QByteArray& data) {
bool connected = (tcpSocket->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << " is NOT connected!";
return;
}
tcpSocket->write(data);
tcpSocket->flush();
}
void Client::readData()
{
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
return;
}
emit dataReceived(data);
}
void Client::onConnectionStateChanged(QAbstractSocket::SocketState state)
{
switch (state) {
case QAbstractSocket::UnconnectedState:
connectionState = "Not connected";
break;
case QAbstractSocket::ConnectingState:
connectionState = "connecting";
break;
case QAbstractSocket::ConnectedState:
connectionState = "connected";
break;
default:
connectionState = QString::number(state);
}
qDebug() << TAG << " connecting state: " << state;
emit connectionStateChanged(connectionState);
if (state == QAbstractSocket::UnconnectedState) {
QTimer::singleShot(1000, this, &Client::reconnect);
}
}
and here the server part:
Server::Server()
{
tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this, &Server::handleConnection);
tcpServer->listen(QHostAddress::Any, 59723);
QString ipAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
qDebug() << TAG << "ip " << ipAddress << " serverport: " << tcpServer->serverPort();
}
void Server::clientDisconnected()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(QObject::sender());
int idx = clients.indexOf(client);
if (idx != -1) {
clients.removeAt(idx);
}
qDebug() << TAG << "client disconnected: " << client;
client->deleteLater();
}
void Server::handleConnection()
{
qDebug() << TAG << "incoming!";
QTcpSocket* clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, &QAbstractSocket::disconnected, this, &Server::clientDisconnected);
connect(clientConnection, &QIODevice::readyRead, this, &Server::readData);
clients.append(clientConnection);
broadcastUpdate(Assets().toJson());
}
void Server::readData()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(QObject::sender());
QDataStream in(client);
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
return;
}
...
// here I do something with the data. I removed that code as it is
// not necessary for this issue
...
broadcastUpdate(data);
}
void Server::broadcastUpdate(const QString& data)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << data;
foreach(QTcpSocket* client, clients) {
bool connected = (client->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << client << " is NOT connected!";
continue;
}
client->write(block);
}
}
I think the problem is with your void Client::readData(): you have to write it in such a way that you read all available data from the socket inside it (usually it's written with while (socket->bytesAvailable() > 0) { ... } loop).
It is because of the way the readyRead() signal is emitted: the remote peer may send any non-zero number of packets to you, and your socket will emit any non-zero number of readyRead() signals. In your case, it seems that the server sends two messages but they only cause one readyRead() signal to be emitted on the client.

unable to establish two way communication using qt

I have used QTcpSocket and QTcpServer class of qt to establish two way communication. I am able to send data from client to server. But am not getting the response back from server i.e my client.cpp never fires readyRead() signal. I have checked using Wireshark that my data from the server is available in specifed port.
I am posting my client.cpp code( Please help) :
Client::Client(QObject* parent): QObject(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),
this, SLOT(startTransfer()));
connect(socket, SIGNAL(readyRead()),this, SLOT(startRead()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)) );
}
Client::~Client()
{
socket->close();
}
void Client::start(QString address, quint16 port)
{
addr.setAddress(address);
socket->connectToHost(addr,port,QTcpSocket::ReadWrite);
}
void Client::startTransfer()
{
printf("Connection established.\n");
char buffer[1024];
forever
{
printf(">> ");
gets(buffer);
int len = strlen(buffer);
buffer[len] = '\n';
buffer[len+1] = '\0';
socket->write(buffer);
socket->flush();
}
}
void Client::startRead()
{
cout<<"inside startRead()<<endl";
while(socket->canReadLine())
{
QByteArray ba = socket->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
socket->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
}
}
void Client::socketError(QAbstractSocket::SocketError )
{
qDebug()<<"error" ;
}
Looks like you have forever loop here. This means that your Qt main eventloop never gets the control back after you call startTransfer(). How do you suppose the Qt should run the startRead() code if you block your execution thread with infinite loop?
For Amartel adding the server code:
Server::Server(QObject* parent): QObject(parent)
{
// cout << "Before connect" << endl;
connect(&server, SIGNAL(newConnection()),
this, SLOT(acceptConnection()));
cout << "Listening.." << endl;
server.listen(QHostAddress::Any, 9999);
// cout << "Server started.." << endl;
}
Server::~Server()
{
server.close();
}
void Server::acceptConnection()
{
// cout << "In acceptConnection" << endl;
client = server.nextPendingConnection();
connect(client, SIGNAL(readyRead()),
this, SLOT(startRead()));
}
void Server::startRead()
{
while(client->canReadLine())
{
QByteArray ba = client->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
client->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
int result = 0;
bool ack = true;
result = client->write("I Reached");
cout<<result<<endl;
if(result <= 0)
qDebug("Ack NOT sent to client!!!");
else
qDebug("Ack sent to client.");
// client->write("I Reached");
client->flush();
}
}

QTcpSocket stucks sometimes for dynamic created java script

I am trying to connect to a website through a proxy. I implemented a QTcpServer and a QTcpSocket.
The server passes the connection to the socket.
It works well, but for some sites, expecially for those which have dynamically created javascript, the socket stucks at some point and nothing is shown in the navigator.
Attach the code, hope clear.
#include "webproxy.h"
#include <QtNetwork>
#include <QMessageBox>
#include <QtGui>
#include <QHash>
WebProxy::WebProxy(QObject *parent,int port): QObject(parent)
{
qDebug()<<" Listen...";
authMethod = "";
QTcpServer *proxyServer = new QTcpServer(this);
if (!proxyServer->listen(QHostAddress::Any, port)) {
emit error(1);
return;
}
connect(proxyServer, SIGNAL(newConnection()), this, SLOT(manageQuery()));
qDebug() << "Proxy server running at port" << proxyServer->serverPort();
void WebProxy::manageQuery() {
QTcpServer *proxyServer = qobject_cast<QTcpServer*>(sender());
QTcpSocket *socket = proxyServer->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(processQuery()));
connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
qDebug()<<"New connection started..."<<socket->peerAddress();
}
QUrl WebProxy::getUrl(QList<QByteArray > &entries)
{
QByteArray method = entries.value(0);
QByteArray address = entries.value(1);
QByteArray version = entries.value(2);
qDebug()<<method;
qDebug()<<address;
qDebug()<<version;
QUrl url = QUrl::fromEncoded(address);
if (!url.isValid()) {
qWarning() << "Invalid URL:" << url;
return QString();
}
return url;
}
void WebProxy::processQuery() {
int wSize = 0;
QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
QByteArray requestData = socket->readAll();
qDebug()<<"Request "<<requestData;
int pos = requestData.indexOf("\r\n");
QByteArray requestLine = requestData.left(pos);
requestData.remove(0, pos + 2);
QList<QByteArray> entries = requestLine.split(' ');
QByteArray method = entries.value(0);
QByteArray address = entries.value(1);
QByteArray version = entries.value(2);
QByteArray auth;
QByteArray authMethod;
QUrl url = QUrl::fromEncoded(address);
if (!url.isValid()) {
qWarning() << "Invalid URL:" << url;
socket->disconnectFromHost();
return;
}
QString host = url.host();
int port = (url.port() <= 0) ? 80 : url.port();
QByteArray req = url.encodedPath();
if (url.hasQuery())
req.append('?').append(url.encodedQuery());
requestLine = method + " " + req + " " + version + "\r\n";
if (!authMethod.isEmpty())
{
requestLine.append(requestLine);
requestLine.append(authMethod);
requestLine.append("\r\n");
}
QString key = host + ':' + QString::number(port);
QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
if (proxySocket) {
proxySocket->setObjectName(key);
proxySocket->setProperty("url", url);
proxySocket->setProperty("requestData", requestData);
wSize = proxySocket->write(requestData);
} else {
proxySocket = new QTcpSocket(socket);
proxySocket->setObjectName(key);
proxySocket->setProperty("url", url);
proxySocket->setProperty("requestData", requestData);
connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
proxySocket->connectToHost(host, port);
}
}
void WebProxy::sendRequest() {
QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
QByteArray requestData = proxySocket->property("requestData").toByteArray();
int wSize = 0;
wSize = proxySocket->write(requestData);
}
void WebProxy::transferData() {
QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
QByteArray data = proxySocket->readAll();
qDebug()<<"READ TRANSFER SIZE..."<<data.size();
QString host = proxySocket->peerAddress().toString();
QByteArray filtered(data);
QTcpSocket *socket = qobject_cast<QTcpSocket*>(proxySocket->parent());
int wSize = 0;
if (!data.trimmed().isEmpty())
{
wSize = socket->write(filtered);
if (wSize==-1)
qDebug()<<"WP error";
else
qDebug()<<"TRANSFER WRITE SIZE = "<<wSize<<" READ SIZE"<<filtered.size();
}
}
void WebProxy::closeConnection() {
QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
if (proxySocket) {
QTcpSocket *socket = qobject_cast<QTcpSocket*>(proxySocket->parent());
if (socket)
socket->disconnectFromHost();
if (proxySocket->error() != QTcpSocket::RemoteHostClosedError)
qWarning() << "Error for:" << proxySocket->property("url").toUrl()
<< proxySocket->errorString();
proxySocket->deleteLater();;
}
}
You may want to use QTcpServer in a multi-threaded way.
Subclass QTcpServer, overload QTcpServer::incomingConnection(int), create your QThread derived handler (described next) and start it with QThread::start
Subclass QThread, make the constructor accept an int (the socket descriptor), overload QThread::run(). In the run function, create QTcpSocket, call QAbstractSocket::setSocketDescriptor to initialise the socket, connect up the socket slots and call QThread::exec() to start the thread event loop.
Make sure you create the socket in the run of QThread, not the constructor so the socket is associated with that thread.
For more details, look at the Threaded Fortune Server Example

Resources