unable to send data via QTcpSocket
-
im making a client that needs to send files back and forth, right now i want to send only a single string but for some reason it wont send anything even when the tcp socket is open, the server is working on another machine and its writen in python, it works i already check using another client writen in python with websockets
on the header file
private: QTcpSocket *TCP_socket; QDataStream data; QString CurrentData;
when i call this function, it should connect, so far so good it supose it works
void Server::TCP_Request(){ Gen L; QString Ip("192.168.1.67"); TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip if (TCP_socket->isOpen()){ L.Log("coneccion"); } }
According to the tutorial i did follow here Qt fortune client , when the connection its made the &QTcpSocket::readyRead signal should trigger the lambda, it connect but i cant trigger the lambda
Server::Server(){ Gen gen; TCP_socket = new QTcpSocket(); //data.setDevice(TCP_socket); //data.setVersion(QDataStream::Qt_DefaultCompiledVersion); QObject::connect(TCP_socket, &QTcpSocket::readyRead, [&](){ gen.Log("dentro de readyRead"); QString dataread; QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Data"); MBox.setDefaultButton(boton_OK); data.startTransaction(); data >> dataread; if(!data.commitTransaction()){ return; } gen.Log(dataread); MBox.setText(dataread); MBox.exec(); });
also i did follow the error management from the same tutorial but the signal from &QAbstractSocket::errorOcurred its not working on my Qt version i use Qt 5.11 and i cant upgrade so im stuck to this particualer version, i did try to upgrade to 5.15 and 6 but it wont work for some reason
QObject::connect(TCP_socket, &QAbstractSocket::errorOcurred, [&](QAbstractSocket::SocketError error){ QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Error "); MBox.setDefaultButton(boton_OK); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } }); }
i did read on another threat how to send the file but im unable to even send a string
-
im making a client that needs to send files back and forth, right now i want to send only a single string but for some reason it wont send anything even when the tcp socket is open, the server is working on another machine and its writen in python, it works i already check using another client writen in python with websockets
on the header file
private: QTcpSocket *TCP_socket; QDataStream data; QString CurrentData;
when i call this function, it should connect, so far so good it supose it works
void Server::TCP_Request(){ Gen L; QString Ip("192.168.1.67"); TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip if (TCP_socket->isOpen()){ L.Log("coneccion"); } }
According to the tutorial i did follow here Qt fortune client , when the connection its made the &QTcpSocket::readyRead signal should trigger the lambda, it connect but i cant trigger the lambda
Server::Server(){ Gen gen; TCP_socket = new QTcpSocket(); //data.setDevice(TCP_socket); //data.setVersion(QDataStream::Qt_DefaultCompiledVersion); QObject::connect(TCP_socket, &QTcpSocket::readyRead, [&](){ gen.Log("dentro de readyRead"); QString dataread; QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Data"); MBox.setDefaultButton(boton_OK); data.startTransaction(); data >> dataread; if(!data.commitTransaction()){ return; } gen.Log(dataread); MBox.setText(dataread); MBox.exec(); });
also i did follow the error management from the same tutorial but the signal from &QAbstractSocket::errorOcurred its not working on my Qt version i use Qt 5.11 and i cant upgrade so im stuck to this particualer version, i did try to upgrade to 5.15 and 6 but it wont work for some reason
QObject::connect(TCP_socket, &QAbstractSocket::errorOcurred, [&](QAbstractSocket::SocketError error){ QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Error "); MBox.setDefaultButton(boton_OK); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } }); }
i did read on another threat how to send the file but im unable to even send a string
@Lightshadown said in unable to send data via QTcpSocket:
when the connection its made the
&QTcpSocket::readyRead
signal should trigger the lambdaNo, connecting does not fire this. Only if the server sends some data would this be emitted, no reason to suppose your Python server does that.
Your question talks about failure to send any data, yet your code does not attempt to send any data, only read data. Maybe that is all your problem is?
QObject::connect(TCP_socket, &QAbstractSocket::errorOcurred, [&](QAbstractSocket::SocketError error){ ...
This line will not compile. So either that is what you mean by "but it wont work for some reason" --- in which case it would be much better to state that it does not compile --- or it means you have not copied & pasted your actual, compilable, working code --- in which case, from experience answering questions here, all bets are off.
Back in Qt 5.11 you still have an error signal, just it used to be called
error()
instead.I suggest you start by connecting the client's
stateChanged()
signal and seeing what changes it undergoes. -
@Lightshadown said in unable to send data via QTcpSocket:
when the connection its made the
&QTcpSocket::readyRead
signal should trigger the lambdaNo, connecting does not fire this. Only if the server sends some data would this be emitted, no reason to suppose your Python server does that.
Your question talks about failure to send any data, yet your code does not attempt to send any data, only read data. Maybe that is all your problem is?
QObject::connect(TCP_socket, &QAbstractSocket::errorOcurred, [&](QAbstractSocket::SocketError error){ ...
This line will not compile. So either that is what you mean by "but it wont work for some reason" --- in which case it would be much better to state that it does not compile --- or it means you have not copied & pasted your actual, compilable, working code --- in which case, from experience answering questions here, all bets are off.
Back in Qt 5.11 you still have an error signal, just it used to be called
error()
instead.I suggest you start by connecting the client's
stateChanged()
signal and seeing what changes it undergoes.@JonB ok you are right, i was calling the wrong instance heres my actual code that works when im connecting to the server, i use QTcpSocket::connected yet im unable to send any data to the server, my problem comes when im using TCP_socket->write(block) it supose im sending the data in here, but my program freeze everytime it reachs this point.
QObject::connect(TCP_socket, &QTcpSocket::connected, [&](){ QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Servidor"); MBox.setDefaultButton(boton_OK); MBox.setText("Conectado"); gen.Log("tcp conectado"); bool yes; QByteArray block; QString dataSend; QDataStream data(&block, QIODevice::ReadWrite); //data << (quint16)0; dataSend.append("Sending data"); data << dataSend; //data.device()->seek(0); //data <<(quint16)(block.size()) - sizeof(quint16); gen.Log("antes de escribir"); //TCP_socket->write(block.size()); TCP_socket->write(block); gen.Log("despues de escribir"); yes = TCP_socket->waitForBytesWritten(); gen.Log("despues de esperar"); if (yes == true){ MBox.exec();} else {MBox.setText("Hay pedo"); MBox.exec();} TCP_socket->disconnectFromHost(); gen.Log("coneecion terminada"); } );
Also i try to use the error handling but i allways get the follow error while using connect and wont compile, no matching function for call to 'QObject::connect(QTcpSocket/&, <unresolved overloaded function type>, Server::Server()::<lambda()>) i have to use lambdas because the normal slot methods also give me errors
QObject::connect(TCP_socket, &QTcpSocket::error, [&](){ QTcpSocket::SocketError error; QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Error "); MBox.setDefaultButton(boton_OK); error = TCP_socket->error(); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } });
if i try to use the normal slots system for the tcp socket i got, template argument deduction/substitution failed
QObject::connect(TCP_socket, &QTcpSocket::error, this, &Server::displayError);
-
Hi,
As already suggested, you should use the errorOccured signal.
-
@SGaist ok i just read all the documentation for my version of Qt 5.11, and im using TCP_socket->errorString() the reason why, is beacuse im not having the error signal been trigger, but if i use the errorstring function i get and Unknown error, the port is open, the port is writable and yet im unable to trigger any signal or write anything, in fact my program crash everytime, i even had to do a static_cast on the error handling so it can compile, i add my actual code below
Server::Server(){ Gen gen; TCP_socket = new QTcpSocket(); QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setDefaultButton(boton_OK); //data.setDevice(TCP_socket); //data.setVersion(QDataStream::Qt_DefaultCompiledVersion); QObject::connect(TCP_socket, &QTcpSocket::connected, [&](){ // escrituta cuando se conecta MBox.setWindowTitle("Servidor"); MBox.setText("Conectado"); gen.Log("tcp conectado"); bool yes; QByteArray block("Hola motherfucker, from laptop"); //QString dataSend; // QDataStream data(&block, QIODevice::ReadWrite); // //data << (quint16)0; // dataSend.append("Enviando desde laptop"); // data << dataSend; //data.device()->seek(0); //data <<(quint16)(block.size()) - sizeof(quint16); gen.Log("antes de escribir"); //TCP_socket->write(block.size()); TCP_socket->write(block); gen.Log("despues de escribir"); yes = TCP_socket->waitForBytesWritten(); gen.Log("despues de esperar"); if (yes == true){ MBox.exec();} else {MBox.setText("Hay pedo"); MBox.exec();} TCP_socket->disconnectFromHost(); gen.Log("coneecion terminada"); } ); QObject::connect(TCP_socket, &QTcpSocket::readyRead, [&](){ // lectura de datos gen.Log("dentro de readyRead"); QString dataread; QByteArray data; MBox.setWindowTitle("Data Read"); data = TCP_socket->readAll(); dataread.append(data); MBox.setText("leido: " + dataread); gen.Log(dataread); MBox.exec(); }); // manejo de erores //QObject::connect(TCP_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), [&](QAbstractSocket::SocketError error) { QObject::connect(TCP_socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)> (&QAbstractSocket::error), [&](QAbstractSocket::SocketError error){ gen.Log("Error"); MBox.setWindowTitle("Error "); //error = TCP_socket->error(); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } }); QObject::connect(TCP_socket, &QTcpSocket::disconnected, [&](){ gen.Log("Desconectado del servidor"); TCP_socket->deleteLater(); }); } Server::~Server(){ } void Server::TCP_Request(){ // this one is been called from another class and triggers everything Gen L; QString Ip("192.168.1.70"); L.Log("antes de coneccion"); TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip //TCP_socket->waitForConnected(5000); if (TCP_socket->isOpen()){ L.Log("esta abierto el puerto"); } else { L.Log("no esta abierto el puerto"); } if(TCP_socket->isWritable()){ L.Log("Se puede escribir"); } else { L.Log("No se puede usar el puerto"); } L.Log("Error en el socket: " + TCP_socket->errorString()); // switch (TCP_socket->state()){ // case QAbstractSocket::UnconnectedState: // L.Log("sin coneccion"); // case QAbstractSocket::ConnectingState: // L.Log("Conecctando..."); // case QAbstractSocket::ConnectedState: // L.Log("Coneccion exitosa"); // } }
-
@SGaist ok i just read all the documentation for my version of Qt 5.11, and im using TCP_socket->errorString() the reason why, is beacuse im not having the error signal been trigger, but if i use the errorstring function i get and Unknown error, the port is open, the port is writable and yet im unable to trigger any signal or write anything, in fact my program crash everytime, i even had to do a static_cast on the error handling so it can compile, i add my actual code below
Server::Server(){ Gen gen; TCP_socket = new QTcpSocket(); QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setDefaultButton(boton_OK); //data.setDevice(TCP_socket); //data.setVersion(QDataStream::Qt_DefaultCompiledVersion); QObject::connect(TCP_socket, &QTcpSocket::connected, [&](){ // escrituta cuando se conecta MBox.setWindowTitle("Servidor"); MBox.setText("Conectado"); gen.Log("tcp conectado"); bool yes; QByteArray block("Hola motherfucker, from laptop"); //QString dataSend; // QDataStream data(&block, QIODevice::ReadWrite); // //data << (quint16)0; // dataSend.append("Enviando desde laptop"); // data << dataSend; //data.device()->seek(0); //data <<(quint16)(block.size()) - sizeof(quint16); gen.Log("antes de escribir"); //TCP_socket->write(block.size()); TCP_socket->write(block); gen.Log("despues de escribir"); yes = TCP_socket->waitForBytesWritten(); gen.Log("despues de esperar"); if (yes == true){ MBox.exec();} else {MBox.setText("Hay pedo"); MBox.exec();} TCP_socket->disconnectFromHost(); gen.Log("coneecion terminada"); } ); QObject::connect(TCP_socket, &QTcpSocket::readyRead, [&](){ // lectura de datos gen.Log("dentro de readyRead"); QString dataread; QByteArray data; MBox.setWindowTitle("Data Read"); data = TCP_socket->readAll(); dataread.append(data); MBox.setText("leido: " + dataread); gen.Log(dataread); MBox.exec(); }); // manejo de erores //QObject::connect(TCP_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), [&](QAbstractSocket::SocketError error) { QObject::connect(TCP_socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)> (&QAbstractSocket::error), [&](QAbstractSocket::SocketError error){ gen.Log("Error"); MBox.setWindowTitle("Error "); //error = TCP_socket->error(); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } }); QObject::connect(TCP_socket, &QTcpSocket::disconnected, [&](){ gen.Log("Desconectado del servidor"); TCP_socket->deleteLater(); }); } Server::~Server(){ } void Server::TCP_Request(){ // this one is been called from another class and triggers everything Gen L; QString Ip("192.168.1.70"); L.Log("antes de coneccion"); TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip //TCP_socket->waitForConnected(5000); if (TCP_socket->isOpen()){ L.Log("esta abierto el puerto"); } else { L.Log("no esta abierto el puerto"); } if(TCP_socket->isWritable()){ L.Log("Se puede escribir"); } else { L.Log("No se puede usar el puerto"); } L.Log("Error en el socket: " + TCP_socket->errorString()); // switch (TCP_socket->state()){ // case QAbstractSocket::UnconnectedState: // L.Log("sin coneccion"); // case QAbstractSocket::ConnectingState: // L.Log("Conecctando..."); // case QAbstractSocket::ConnectedState: // L.Log("Coneccion exitosa"); // } }
@Lightshadown said in unable to send data via QTcpSocket:
TCP_socket->write(block);
Up to here you did NOT connect error() signal!
Please connect this signal BEFORE you try to send any data. -
@JonB ok you are right, i was calling the wrong instance heres my actual code that works when im connecting to the server, i use QTcpSocket::connected yet im unable to send any data to the server, my problem comes when im using TCP_socket->write(block) it supose im sending the data in here, but my program freeze everytime it reachs this point.
QObject::connect(TCP_socket, &QTcpSocket::connected, [&](){ QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Servidor"); MBox.setDefaultButton(boton_OK); MBox.setText("Conectado"); gen.Log("tcp conectado"); bool yes; QByteArray block; QString dataSend; QDataStream data(&block, QIODevice::ReadWrite); //data << (quint16)0; dataSend.append("Sending data"); data << dataSend; //data.device()->seek(0); //data <<(quint16)(block.size()) - sizeof(quint16); gen.Log("antes de escribir"); //TCP_socket->write(block.size()); TCP_socket->write(block); gen.Log("despues de escribir"); yes = TCP_socket->waitForBytesWritten(); gen.Log("despues de esperar"); if (yes == true){ MBox.exec();} else {MBox.setText("Hay pedo"); MBox.exec();} TCP_socket->disconnectFromHost(); gen.Log("coneecion terminada"); } );
Also i try to use the error handling but i allways get the follow error while using connect and wont compile, no matching function for call to 'QObject::connect(QTcpSocket/&, <unresolved overloaded function type>, Server::Server()::<lambda()>) i have to use lambdas because the normal slot methods also give me errors
QObject::connect(TCP_socket, &QTcpSocket::error, [&](){ QTcpSocket::SocketError error; QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setWindowTitle("Error "); MBox.setDefaultButton(boton_OK); error = TCP_socket->error(); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } });
if i try to use the normal slots system for the tcp socket i got, template argument deduction/substitution failed
QObject::connect(TCP_socket, &QTcpSocket::error, this, &Server::displayError);
@Lightshadown said in unable to send data via QTcpSocket:
yes = TCP_socket->waitForBytesWritten();
also do not use blocking calls when you're already using signals. QTcpSocket has the bytesWritten signal for this.
Also,also, please remove the
QMessageBox
from the lambda body.Currently you're mixing synchronous and asynchronous apis and sprinkle some additional event loops in. Those 3 should never meet.
-
@Lightshadown said in unable to send data via QTcpSocket:
TCP_socket->write(block);
Up to here you did NOT connect error() signal!
Please connect this signal BEFORE you try to send any data.@jsulm the error handler is already connected but forgot to uncomment on the one i posted my bad, this is the one i used
error = TCP_socket->error();
, still i can access the lambda but the switch statement fails for some reason, i did updated the switch and added all the errors that comes from the enum and it still fails, i have a problem with the error handler and already tried to use my Log function that accept QString, but it crash onces i use theerror
variable@J-Hilk ok sorry on that one didnt pay attention, i already erased all the QMessageBox, so its working properly until i reach
TCP_socket->write
i suspect its my server, its writen in python, it works but only for the first string i did check using another client writen in pythonedit: i simply added
TPC_socket->flush()
and it kinda works, it behaves like the data is already send and even disconect from the server at the end but the data its not recieved on my serverimport asyncio import websockets import socket import sqlite3 def get_ip(): # returns primary private IP only s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) IP = s.getsockname()[0] except Exception: IP = '127.0.0.1' finally: s.close() return IP async def handle_connectio(websocket, path): # recive and handle connection from client, would handle json or file data try: async for name in websocket: #name = await websocket.recv() print(f"<<< {name}") except websocket.exceptions.ConnectionClosed as e: print (f"Coneecion terminada") print ("Iniciando el Server webSocket") print ("Current Ip: " + get_ip()) servidor = websockets.serve(handle_connectio, get_ip(), 8000) asyncio.get_event_loop().run_until_complete(servidor) asyncio.get_event_loop().run_forever() #async def main(): # main function # print ("Iniciando Server websocket") # print("Current Ip: " + get_ip()) # async with websockets.serve(handle_connectio, get_ip(), 8000): # await asyncio.Future() #if __name__ == '__main__': # asyncio.run(main())
-
@SGaist ok i just read all the documentation for my version of Qt 5.11, and im using TCP_socket->errorString() the reason why, is beacuse im not having the error signal been trigger, but if i use the errorstring function i get and Unknown error, the port is open, the port is writable and yet im unable to trigger any signal or write anything, in fact my program crash everytime, i even had to do a static_cast on the error handling so it can compile, i add my actual code below
Server::Server(){ Gen gen; TCP_socket = new QTcpSocket(); QMessageBox MBox; QPushButton *boton_OK = MBox.addButton("Ok", QMessageBox::AcceptRole); MBox.setDefaultButton(boton_OK); //data.setDevice(TCP_socket); //data.setVersion(QDataStream::Qt_DefaultCompiledVersion); QObject::connect(TCP_socket, &QTcpSocket::connected, [&](){ // escrituta cuando se conecta MBox.setWindowTitle("Servidor"); MBox.setText("Conectado"); gen.Log("tcp conectado"); bool yes; QByteArray block("Hola motherfucker, from laptop"); //QString dataSend; // QDataStream data(&block, QIODevice::ReadWrite); // //data << (quint16)0; // dataSend.append("Enviando desde laptop"); // data << dataSend; //data.device()->seek(0); //data <<(quint16)(block.size()) - sizeof(quint16); gen.Log("antes de escribir"); //TCP_socket->write(block.size()); TCP_socket->write(block); gen.Log("despues de escribir"); yes = TCP_socket->waitForBytesWritten(); gen.Log("despues de esperar"); if (yes == true){ MBox.exec();} else {MBox.setText("Hay pedo"); MBox.exec();} TCP_socket->disconnectFromHost(); gen.Log("coneecion terminada"); } ); QObject::connect(TCP_socket, &QTcpSocket::readyRead, [&](){ // lectura de datos gen.Log("dentro de readyRead"); QString dataread; QByteArray data; MBox.setWindowTitle("Data Read"); data = TCP_socket->readAll(); dataread.append(data); MBox.setText("leido: " + dataread); gen.Log(dataread); MBox.exec(); }); // manejo de erores //QObject::connect(TCP_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), [&](QAbstractSocket::SocketError error) { QObject::connect(TCP_socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)> (&QAbstractSocket::error), [&](QAbstractSocket::SocketError error){ gen.Log("Error"); MBox.setWindowTitle("Error "); //error = TCP_socket->error(); switch(error){ case QAbstractSocket::RemoteHostClosedError: MBox.setText("El servidor Cerro la coneccion, Error 500"); MBox.exec(); break; case QAbstractSocket::HostNotFoundError: MBox.setText("No se encontro el Servidor, Error 404"); MBox.exec(); break; case QAbstractSocket::ConnectionRefusedError: MBox.setText("La coneccion fue rechazada por el Servidor, Error 403"); MBox.exec(); break; default: MBox.setText("Hubo un error inesperado: " + TCP_socket->errorString()); MBox.exec(); } }); QObject::connect(TCP_socket, &QTcpSocket::disconnected, [&](){ gen.Log("Desconectado del servidor"); TCP_socket->deleteLater(); }); } Server::~Server(){ } void Server::TCP_Request(){ // this one is been called from another class and triggers everything Gen L; QString Ip("192.168.1.70"); L.Log("antes de coneccion"); TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip //TCP_socket->waitForConnected(5000); if (TCP_socket->isOpen()){ L.Log("esta abierto el puerto"); } else { L.Log("no esta abierto el puerto"); } if(TCP_socket->isWritable()){ L.Log("Se puede escribir"); } else { L.Log("No se puede usar el puerto"); } L.Log("Error en el socket: " + TCP_socket->errorString()); // switch (TCP_socket->state()){ // case QAbstractSocket::UnconnectedState: // L.Log("sin coneccion"); // case QAbstractSocket::ConnectingState: // L.Log("Conecctando..."); // case QAbstractSocket::ConnectedState: // L.Log("Coneccion exitosa"); // } }
@Lightshadown said in unable to send data via QTcpSocket:
TCP_socket = new QTcpSocket();
You are shadowing your class member variable of the same name and likely have a warning about that when you compile.@Lightshadown said in unable to send data via QTcpSocket:
void Server::TCP_Request(){ // this one is been called from another class and triggers everything
Gen L;
QString Ip("192.168.1.70");
L.Log("antes de coneccion");
TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip
//TCP_socket->waitForConnected(5000);Using an uninitialized variable and thus crash.[edit: must have been too tired, I thought I saw the variable declared within the constructor... SGaist]
-
@Lightshadown said in unable to send data via QTcpSocket:
TCP_socket = new QTcpSocket();
You are shadowing your class member variable of the same name and likely have a warning about that when you compile.@Lightshadown said in unable to send data via QTcpSocket:
void Server::TCP_Request(){ // this one is been called from another class and triggers everything
Gen L;
QString Ip("192.168.1.70");
L.Log("antes de coneccion");
TCP_socket->connectToHost( Ip, 8000 ); // do a broadcast and search for servers ip
//TCP_socket->waitForConnected(5000);Using an uninitialized variable and thus crash.[edit: must have been too tired, I thought I saw the variable declared within the constructor... SGaist]
@SGaist that socket was declared as private on the class declaration
class Server { public: Server(); virtual ~Server(); void TCP_Request(); public slots: private: QTcpSocket *TCP_socket = nullptr; };
-
@SGaist that socket was declared as private on the class declaration
class Server { public: Server(); virtual ~Server(); void TCP_Request(); public slots: private: QTcpSocket *TCP_socket = nullptr; };
@Lightshadown said in unable to send data via QTcpSocket:
class Server {
public:
Server();
virtual ~Server();
void TCP_Request();
public slots:
private:
QTcpSocket *TCP_socket = nullptr;
};If you want to declare slots (or signals) in your class, you have to:
- subclass
QObject
(or aQObject
based class) - add
Q_OBJECT
declaration
so you class should be:
class Server : public QObject { Q_OBJECT public: explicit Server(QObject * parent=nullptr); virtual ~Server(); void TCP_Request(); public slots: private: QTcpSocket *TCP_socket = nullptr; };
- subclass
-
ok i ditched the lambda and used a normal function, for some reason it wont work inside the connect signal, but now the socket its lock, and got the error
QAbstractSocket::UnfinishedSocketOperationError i have to restart both machines to free the socket, any idea how to free the socket or check the socket if its aviable?void Server::TCP_Request(){ Gen L; QString Ip("192.168.1.70"); L.Log("antes de coneccion"); TCP_socket->abort(); TCP_socket->connectToHost( Ip, 8000, QIODevice::ReadWrite ); // do a broadcast and search for servers ip L.Log("tcp conectado"); bool yes = false; QByteArray block("Hola, from laptop"); //QDataStream salida(&block, QIODevice::WriteOnly); //salida << "Enviando desde laptop "; //block.append("Enviando desde Laptop"); if (TCP_socket->isValid()) { L.Log("antes de escribir"); TCP_socket->write(block); yes = TCP_socket->flush(); //TCP_socket->waitForBytesWritten(100); } if (yes == true){ L.Log("datos enviados");} else {L.Log("no se envio los datos");} TCP_socket->disconnectFromHost(); //TCP_socket->abort(); L.Log("coneecion terminada"); }
-
ok i ditched the lambda and used a normal function, for some reason it wont work inside the connect signal, but now the socket its lock, and got the error
QAbstractSocket::UnfinishedSocketOperationError i have to restart both machines to free the socket, any idea how to free the socket or check the socket if its aviable?void Server::TCP_Request(){ Gen L; QString Ip("192.168.1.70"); L.Log("antes de coneccion"); TCP_socket->abort(); TCP_socket->connectToHost( Ip, 8000, QIODevice::ReadWrite ); // do a broadcast and search for servers ip L.Log("tcp conectado"); bool yes = false; QByteArray block("Hola, from laptop"); //QDataStream salida(&block, QIODevice::WriteOnly); //salida << "Enviando desde laptop "; //block.append("Enviando desde Laptop"); if (TCP_socket->isValid()) { L.Log("antes de escribir"); TCP_socket->write(block); yes = TCP_socket->flush(); //TCP_socket->waitForBytesWritten(100); } if (yes == true){ L.Log("datos enviados");} else {L.Log("no se envio los datos");} TCP_socket->disconnectFromHost(); //TCP_socket->abort(); L.Log("coneecion terminada"); }
@Lightshadown said in unable to send data via QTcpSocket:
TCP_socket->disconnectFromHost();
You are disconnecting without knowing whether all data was sent (flush() does not guarantee this!).
You should listen to https://doc.qt.io/qt-5/qiodevice.html#bytesWritten signal and disconnect when all data was sent. -
@Lightshadown said in unable to send data via QTcpSocket:
TCP_socket->disconnectFromHost();
You are disconnecting without knowing whether all data was sent (flush() does not guarantee this!).
You should listen to https://doc.qt.io/qt-5/qiodevice.html#bytesWritten signal and disconnect when all data was sent.@jsulm ok i did try using
waitForBytesWritten()
and it kinda works, now i can send the data to the server, and i just had to wait for the socket to connect,waitForConnected(1000)
like it followsvoid Server::TCP_Request(){ Gen L; QString Ip("192.168.1.70"); bool yes = false; QByteArray block("Hola, from laptop"); TCP_socket->abort(); if (TCP_socket->state() == QAbstractSocket::UnconnectedState){ L.Log("antes de coneccion"); TCP_socket->connectToHost( Ip, 8000, QIODevice::ReadWrite ); // do a broadcast and search for servers ip //QDataStream salida(&block, QIODevice::WriteOnly); //salida << "Enviando desde laptop "; //block.append("Enviando desde Laptop"); if (TCP_socket->waitForConnected(1000)){ if (TCP_socket->isValid()) { // && TCP_socket->state() == QAbstractSocket::ConnectedState) { L.Log("antes de escribir"); TCP_socket->write(block); yes = TCP_socket->flush(); TCP_socket->waitForBytesWritten(1000); } } if (yes == true){ L.Log("datos enviados");} else {L.Log("no se envio los datos");} TCP_socket->disconnectFromHost(); TCP_socket->close(); //TCP_socket->abort(); L.Log("coneecion terminada"); } }
also i would check the signal bytes emited and try to figure it out when all the data is sent, next i would check sending files, thanks
-
@jsulm ok i did try using
waitForBytesWritten()
and it kinda works, now i can send the data to the server, and i just had to wait for the socket to connect,waitForConnected(1000)
like it followsvoid Server::TCP_Request(){ Gen L; QString Ip("192.168.1.70"); bool yes = false; QByteArray block("Hola, from laptop"); TCP_socket->abort(); if (TCP_socket->state() == QAbstractSocket::UnconnectedState){ L.Log("antes de coneccion"); TCP_socket->connectToHost( Ip, 8000, QIODevice::ReadWrite ); // do a broadcast and search for servers ip //QDataStream salida(&block, QIODevice::WriteOnly); //salida << "Enviando desde laptop "; //block.append("Enviando desde Laptop"); if (TCP_socket->waitForConnected(1000)){ if (TCP_socket->isValid()) { // && TCP_socket->state() == QAbstractSocket::ConnectedState) { L.Log("antes de escribir"); TCP_socket->write(block); yes = TCP_socket->flush(); TCP_socket->waitForBytesWritten(1000); } } if (yes == true){ L.Log("datos enviados");} else {L.Log("no se envio los datos");} TCP_socket->disconnectFromHost(); TCP_socket->close(); //TCP_socket->abort(); L.Log("coneecion terminada"); } }
also i would check the signal bytes emited and try to figure it out when all the data is sent, next i would check sending files, thanks
@Lightshadown Actually I suggested to use https://doc.qt.io/qt-5/qiodevice.html#bytesWritten signal instead of doing blocking calls to wait. But it is up to you.