socket server could not receive the message send by client - c++

I use Qt creator 5.5.1 in windows 7.
The complier is VC 2010 32Bits.
I have written a socket client. It could connect well but the message could not be sent to the server.
No error occurs when I debug the program.
char flash_result_data[] ={'0', '0', '0', '0', '0', '0', '0', '0'};
void MainWindow::on_pushBtn_LoadCfg_clicked()
{
if (tcpClient == NULL)
{
tcpClient = new QTcpSocket;
tcpClient->connectToHost(ui->txtIPServer->text(),ui->txtPortServer->text().toInt());
Sleep(1000);
QObject::connect(tcpClient,SIGNAL(readyRead()),this, SLOT(readMessageFromTCPServer()));
QTimer::singleShot(100000, this, SLOT(fun_timer()));
}
}
void MainWindow::readMessageFromTCPServer()
{
QObject::connect(this, SIGNAL( MySignal() ),this, SLOT( MySlot() ) );
std::string r="start";
QByteArray qba;
qba= tcpClient->readAll();
if (qba.contains(r.c_str()))
{
emit MySignal();
}
return;
}
void MainWindow::fun_timer()
{
int flash_result_data_size = sizeof(flash_result_data) / sizeof(char);
std::string flash_result_data_str = convertToString(flash_result_data, flash_result_data_size);
tcpClient->write(flash_result_data_str.c_str(),strlen((flash_result_data_str.c_str())));
}
When I debug the program, the socket could connect well. And after run this line: tcpClient->write(flash_result_data_str.c_str(),strlen((flash_result_data_str.c_str()))); , no error occurs, but there is no message received from socket server.
The socket server is developed by others and is used many times in other similar project so the server must be OK. The problem is my client code. But I do not know where my error is.

At the top of the file add #include<QDebug>.
In MainWindow class header file, add QByteArray qba; as a private member variable.
Change your readMessageFromTCPServer to:
void MainWindow::readMessageFromTCPServer()
{
QObject::connect(this, SIGNAL( MySignal() ),this, SLOT( MySlot() ) );
std::string r="start";
qba.append(tcpClient->readAll());
qDebug() << "BUFFER:" << QString::fromUtf8(qba);
if (qba.contains(r.c_str()))
{
emit MySignal();
}
return;
}
Look at qDebug output to see how the data is being received.
Also, I think this connection is not necessary QObject::connect(this, SIGNAL( MySignal() ),this, SLOT( MySlot() ) );.
You could just call MySlot(); since both the signal and the slot are part of the same object.
if (qba.contains(r.c_str()))
{
MySlot();
}

Related

QT Connect Slot / Signal not working

I am having trouble to connect a Signal to a Slot in the following code:
#include "myserver.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::StartServer()
{
if(listen(QHostAddress::Any, 45451))
{
qDebug() << "Server: started";
emit servComando("Server: started");
}
else
{
qDebug() << "Server: not started!";
emit servComando("Server: not started!");
}
}
void MyServer::incomingConnection(int handle)
{
emit servComando("server: incoming connection, make a client...");
// at the incoming connection, make a client
MyClient *client = new MyClient(this);
client->SetSocket(handle);
//clientes.append(client);
//clientes << client;
connect(client, SIGNAL(cliComando(const QString&)),this, SLOT(servProcesarComando(const QString&)));
// para probar
emit client->cliComando("prueba");
}
void MyServer::servProcesarComando(const QString& texto)
{
emit servComando(texto);
}
The emit client->cliComando("prueba"); works, but the real "emits" don't.
The console does not show any connection error, and the QDebug texts shows everything works well.
Original code was copied from http://www.bogotobogo.com/cplusplus/sockets_server_client_QT.php
I found the problem, Im sending a signal BEFORE connecting:
client->SetSocket(handle);
sends the signal, and Im CONNECTing after it... Now it is:
// at the incoming connection, make a client
MyClient *client = new MyClient(this);
connect(client, SIGNAL(cliComando(const QString&)),this, SLOT(servProcesarComando(const QString&)));
client->SetSocket(handle);
And it works. I noticed it after read the following:
13. Put all connect statements before functions calls that may fire their signals, to ensure that the connections are made before the signals are fired. For example:
_myObj = new MyClass();
connect(_myObj, SIGNAL(somethingHappend()), SLOT(doSomething()));
_myObj->init();
not
_myObj = new MyClass();
_myObj->init();
connect(_myObj, SIGNAL(somethingHappend()), SLOT(doSomething()));
I found it at https://samdutton.wordpress.com/2008/10/03/debugging-signals-and-slots-in-qt/
Anyway, thanks for your answers!

Signal readyRead not emitted, when I create QSerialPort from thread

I have a class COMPort for interaction with QSerialPort. When I create exemplar this class from main thread, then I can send and receive data and signal readyRead will be emitted. But when I try make the same from thread, signal readyRead will be not emitted.
void GetSN_Thread::run()
{
// Connect to serial port with default baudrate
serialPort = new COMPort();
if (!(serialPort->connectCOM(portName, DEFAULT_BAUDRATE)))
{
//Send signal -> Unable connect to this com port
emit showMsg("Unable to connect to " + portName + "\n");
return;
}
emit showMsg(portName + " connected" + "\n");
serialPort->write("Hello");
After this I wait a signal readyRead, but this was not emitted.
When I make this from main thread, then it all works.
serialPort = new COMPort();
QString btlMsg= "";
if (serialPort->connectCOM(comName, comBR))
{
serialPort->write(COMMAND_START);
rcvThr = new ReceiveThread(serialPort, 4);
connect(rcvThr,SIGNAL(sendString(QString)), this, SLOT(msgHandler(QString)));
rcvThr->start();
}
And code for COMPort:
bool COMPort::connectCOM(QString name, int baudrate)
{
this->portName = name;
this->baudrate = baudrate;
connect(&serialPort, SIGNAL(readyRead()), this, SLOT(readDataCOM()));
serialPort.setPortName(this->portName);
serialPort.setDataBits(QSerialPort::Data8);
serialPort.setParity(serialPort.NoParity);
serialPort.setBaudRate((QSerialPort::BaudRate)this->baudrate);
serialPort.setStopBits(serialPort.OneStop);
serialPort.open(QIODevice::ReadWrite);
if (serialPort.isOpen())
return true;
else
return false;
}
Method for reading data:
void COMPort::readDataCOM()
{
char chData;
while (serialPort.read(&chData,1))
{
queueMsg.append(chData);
}
}
Everything ok... but where is signal emitted? I don't see anywhere in code emit readyRead(); and nowhere is connected showMsg(); signal.

client program crashes when connect to server after disconnect Qt

I am implementing client side of TCP-Ip server based on Qt but the program crashes when I closed connection and start again by hitting connect button.
Overview of project. I have Qwidget ( main application) with 2 lineEdit for user to input port number and server Ip address.
It also has 2 button that connect to server and disconnect. On hitting connect button , it will call constructor of client socket and call connectToHost.
Testing: Tried testing on same computer with server running on port 6000 and ip address 127.0.0.1.
Problem: When I launch Client application.And input port number and address and hit connect button it connects successfully. And I can write to server successfully. then I click disconnect button and it disconnects successfully but after that if I connect again by clicking connect button it crashes. I know problem is with tcpSocket but have no idea how to fix it.
clientAgent( QWidget appilciation ).h
namespace Ui {
class ClientAgent;
}
class ClientAgent : public QWidget
{
Q_OBJECT
public:
explicit ClientAgent(QWidget *parent = 0);
~ClientAgent();
private:
Ui::ClientAgent *ui;
ClientForTest *tcpSockForTest;
// Qwidget declartion
below
....
private slots:
void startClient();
void stopClient();
public slots:
void getCliReqTextChanged();
};
ClientAgent.cpp
ClientAgent::ClientAgent( QWidget *parent ) :
QWidget(parent),
ui( new Ui::ClientAgent )
{
// Widget declartion and initilisation
// Layout design etc
//define signals and slots for Client
// signals and slots
connect( btnStartClient, SIGNAL( clicked() ), this, SLOT( startClient() ) );
connect( btnStopClient, SIGNAL( clicked() ), this, SLOT( stopClient() ) );
// for write
connect( lEditCliReq, SIGNAL( textChanged(const QString& ) ), this, SLOT( getCliReqTextChanged() ) );
ui->setupUi( this );
}
ClientAgent::~ClientAgent()
{
delete ui;
}
void ClientAgent::startClient()
{
qDebug() << " we are in strt Clinet";
qDebug() << " connecting ";
// get server address and port number from GUI
QString testAddr = lEditAddr->text();
QString testPort = lEditPrt->text();
tcpSockForTest = new ClientForTest( testAddr, testPort.toInt(), this );
if( tcpSockForTest->connectToServer() == true )
{
lblCliStatus->setText(" connected ....");
}
else
{
lblCliStatus->setText(" failed to connect....");
}
}
void ClientAgent::stopClient()
{
qDebug() << " disconnecting ";
tcpSockForTest->disconnectToServer();
delete tcpSockForTest;
}
ClientForTest.h
class ClientForTest : public QObject
{
Q_OBJECT
public:
ClientForTest( QString hostAddr, quint16 portNum, QObject *parent );
bool connectToServer();
void disconnectToServer();
QString getStoreMsgFrmCliReq( ) const;
void writeToTest(const QString& stripCmd );
void executeSignals();
~ClientForTest();
signals:
void sigSendData();
public slots:
void connectedToTest();
void connectionClosedByServer();
void error();
private:
QTcpSocket *sockFortest;
QString hostName;
quint16 portNumber;
quint16 nextBlockSize;
QString storeLineEditMsg;// store message from lineEditCliReq;
};
ClientForTest.cpp
ClientForTest::ClientForTest( QString hostAddr, quint16 portNum, QObject *parent ) :
hostName( hostAddr ),
portNumber( portNum ),
QObject( parent )
{
connect( sockFortest, SIGNAL( connected() ), this, SLOT( connectedToTest() ) );
connect( sockFortest, SIGNAL( disconnected() ), this, SLOT( connectionClosedByServer() ) );
connect( sockFortest, SIGNAL( error( QAbstractSocket::SocketError ) ), this, SLOT( error() ) );
storeLineEditMsg = "";
}
void ClientForTest::executeSignals()
{
// actually I need toplace itin constructor will do later on
connect( this, SIGNAL( sigSendData() ), this, SLOT( connectedToTest() ) );
}
ClientForTest::~ClientForTest()
{
sockFortest->close();
delete sockFortest;
}
bool ClientForTest::connectToServer()
{
sockFortest = new QTcpSocket( this->parent() ); // COULD be Probelm here but how to fix it?
sockFortest->connectToHost( hostName, portNumber );
nextBlockSize = 0;
executeSignals();
return sockFortest->waitForConnected(1000);
}
void ClientForTest::disconnectToServer()
{
sockFortest->close();
//sockFortest.close();
qDebug() << "in disconnect for Test ";
emit updateLabelinParent( updateStatusDis );
}
void ClientForTest::connectionClosedByServer()
{
qDebug() << "connection closed by server ";
if( nextBlockSize != 0xFFFF )
{
disconnectToServer();
}
}
void ClientForTest::error()
{
qDebug() << "in error ";
disconnectToServer();
}
void ClientForTest::writeToTest( const QString& stripCmd )
{
storeLineEditMsg = stripCmd;
if( sockFortest->state() == QTcpSocket::UnconnectedState )
{
sockFortest->close();
delete sockFortest;
sockFortest = new QTcpSocket( this->parent() );
if( connectToServer() == true )
{
qDebug() << " YEEEE CONNECTED AGAIN finally ";
}
}
if( sockFortest->state() == QTcpSocket::ConnectedState )
{
qDebug() << " YEEEE CONNECTED";
sigSendData();
}
}
void ClientForTest::connectedToTest( )
{
QByteArray block;
QDataStream out( &block, QIODevice::WriteOnly );
out.setVersion( QDataStream::Qt_4_3 );
QString stripCmd = getStoreMsgFrmCliReq(); // received info for some other function I havnt shown that func here
out << quint16( 0 ) << stripCmd;
out.device()->seek( 0 );
out << quint16( block.size() - sizeof( quint16 ) );
qDebug()<<" yeeeee connected state...";
sockFortest->write( block );
//reset storeLineEditMessage
storeLineEditMsg.clear();
}
A few things, that could all together be responsible for your crash:
you connect the signals inside the ClientForTest constructor, but the socket itself is created later. That won't work. Move the line sockFortest = new QTcpSocket(this); to the constructor, before connecting
Same line, use this instead of this->parent()
And finally: There are multiple places you create/delete the socket. Don't do it. Create the socket inside the constructor with this as parent, and that's it. In your connectToServer, establish the connection, and in disconnectToServer, close it using disconnectFromHost. Same goes for the startClient and stopClient. Create the object once and just use the connect/disconnect functions, no deleting.
If code is required, I can add some.
Since it was requested, here is some more explanation:
Of course you can use parent, but in your case, the ClientForTest is an QObject, too. If you set the ClientForTest as as parent of the socket and the widget as the parent of ClientForTest, they will be both cleaned up properly. If you use this->parent(), both will be destroyed "at the same time". However, one comes first and somtimes Qt changes the order, so your socket could be destroyed before the ClientForTest. The destructor of ClientForTest would crash. That won't happen if the socket is a child of the ClientForTest
The main difference between close() and disconnectFromHost() is that the first actually closes the OS socket, while the second does not. The problem is, after a socket was closed, you cannot use it to create a new connection. Thus, if you want to reuse the socket, use disconnectFromHost() otherwise close()
And regarding 3. and 4.:
What you are doing is creating the ClientForTest when the user clicks connect, and delete it as soon as he clicks disconnect. But thats no good design (IMHO). Since tcpSockForTest already is a member of the class, create it (via new) inside the constructor, and delete it in the destructor (optionally, because if you pass the widget as parent, Qt will delete it for you).

device not open error + QIODevice::write

I get the error:
QIODevice::write (QTcpSocket): device not open.
After trying , I think problem is passing parameter server->nextPendingConnection() into object. Can someone has idea how to do it correctly?
My understanding is that object for socketClient is not initialised properly.
I'm using Ubuntu with Qt.
I am implementing server using Qt. The server part has two classes based on QTcpServer and QTcpSocket.
say Server and SocketClient.
I am creating object of SocketClient in server and for testing purpose I opened telnet session and wants to see that server write "hello" on terminal. But somehow its not working. Can someone please advice me where I am making mistake.
Server::Server(QObject *parent) : QObject(parent)
{
server_obj = new QTcpServer( this );
}
void Server::startServer()
{
connect( server_obj, SIGNAL( newConnection() ), this, SLOT( incomingConnection() ) );
if( !server_obj->listen( QHostAddress::Any, 9999) )
{
qDebug() << " Server failed to get started";
}
else
{
qDebug() << " Server started"; // this is successful
}
}
void Server::incomingConnection()
{
socketforClient = new SockClient( server_obj->nextPendingConnection() );// has a doubt on nextPendingconection??
//only for testing remove it
socketforClient->writeToClient();
}
Class for Client
* Description: Its a constructor.I have changed default constructor to add QTcpSocket* object in parameter.I used this constructor in void Server::incomingConnection()
*/
SockClient::SockClient(QObject *parent,QTcpSocket* socket ) : QObject(parent)
{
socketClient = new QTcpSocket( socket );
qDebug() << " we are in constructor of 1st sockclient ";
}
// this is for testing purpose only
void SockClient::writeToClient()
{
socketClient->write(" hello world\r\n");
socketClient->flush();
socketClient->waitForBytesWritten(3000);
}
//header file of SockClient
class SockClient : public QObject
{
Q_OBJECT
public:
explicit SockClient( QObject *parent, QTcpSocket* socket= 0 ); // I have created
void writeToClient(); // This is for testing purpose
~SockClient();
signals:
private slots:
void readClient();
private:
void sendResponsetoMops();
QTcpSocket *socketClient;
quint16 nextBlockSize;
public slots:
};
You use:
socketClient = new QTcpSocket( socket );
Try to use following code instead:
socketClient = socket;
And use
socketforClient = new SockClient(this, server->nextPendingConnection() );
instead of
socketforClient = new SockClient( server->nextPendingConnection() );

how to modify values of dynamically created Widget from different class QT/C++

I know this question has been asked few times but all suggestions given there doesn't work for me.
Overview: I am implementing client server model and wants that as soon as msg arrived in server it should get displayed in main Qt widget. the widget , I choose to display msg is QLineEdit.
I have 3 files in project at the moment. Agent_A which is has all widget created dynamically. Then Server_test based on QTCPServer and sockClient for socket connection. I have received message on sockclient successfully from client but I don't know how to display it correctly on Agent_A .
I have added function in socketClient.cpp to update function in Agent_A but I guess when creating instance it always being NULL.
First a small snippet of my code and then what I have tried. may be you guys can input some valuable info.
Agent_A.h
class Agent_A : public QWidget
{
Q_OBJECT
public:
explicit Agent_A(QWidget *parent = 0);
void setLineEdit( const& modifyStr ); // function to change lineEditCmdString
~Agent_A();
private:
Ui::Agent_A *ui;
QPushButton *buttonStartServer;
QPushButton *buttonStopServer;
// some other widgets
QLabel *labelDisplay;
QLineEdit *lineEditCmdString;// I want to modify this value from sock client
ServerTest *server;
// few slots defined here
}
Agent_A.cpp
Agent_A::Agent_A( QWidget *parent ):
QWidget( parent ),
ui( new Ui::Agent_A )
{
//define push buttons
buttonStartServer = new QPushButton( tr( "&Start Server" ) );
buttonStopServer = new QPushButton( tr( "S&top" ));
// some properties of other widgets defined here which is not relevant to mention here
labelDisplay = new QLabel( tr("DisplayMessgae" ) );
lineEditCmdString = new QLineEdit;// I want to modify this value on sock client
labelDisplay->setBuddy( lineEditCmdString );
// define signals and slots for Server
connect( buttonStartServer, SIGNAL( clicked() ), this, SLOT( startServers() ) );
connect( buttonStopServer, SIGNAL( clicked() ), this, SLOT( stopServer() ) );
// some layout here which agian is not important to mention here.
ui->setupUi( this );
}
Agent_A::~Agent_A()
{
delete ui;
}
void Agent_A::setLineEdit( const Qstring& modifyStr )
{
lineEditCmdString->setText( modifyStr );
}
// now by socket client which creates socket
sockClient.h
class SockClient : public QObject
{
Q_OBJECT
public:
explicit SockClient( QObject *parent, QTcpSocket* socket= 0 );
~SockClient();
// I have added this function to update QLIneEdit in Agent_A
void updateTextinParent(const QString &changeText);
signals:
private slots:
void readClient();
private:
// some other functions
QTcpSocket *socketClient;
quint16 nextBlockSize;
public slots:
};
sockclient.cpp
// constructor for sockclient and some other functions
SockClient::SockClient( QObject *parent, QTcpSocket* socket ) : QObject( parent )
{
socketClient = socket ;
// create signals and slots
connect( socketClient, SIGNAL( readyRead() ), this, SLOT( readClient() ) );
connect( socketClient, SIGNAL( disconnected() ), this, SLOT( deleteLater() ) );
}
SockClient::~SockClient()
{
socketClient->close();
delete socketClient;
}
void SockClient::readClient()
{
QDataStream clientReadStream( socketClient );
clientReadStream.setVersion( QDataStream::Qt_4_3 );
QString strRecvFrm;
quint8 requestType;
clientReadStream >> nextBlockSize;
clientReadStream >> requestType;
if( requestType == 'S')
{
clientReadStream >> strRecvFrm;
}
qDebug() << " the string is " << strRecvFrm; // Has recieved correctly from client
updateTextinParent( strRecvFrmMops ); // Now trying to update widget
socketClient->close();
}
void SockClient::updateTextinParent( const QString& changeText )
{
if( this->parent() == 0 )
{
qDebug() << " Parent not assigned"; // This get printed ..
}
Agent_A *agent = qobject_cast< Agent_A* >( this->parent() ); // ?? is this is right way to do..?
if( agent != NULL )
{
qDebug() << " we are in updateTextin" << changeText; // it never get printed so I assume instance is always nULL
agent->setLineEdit( changeText );
}
}
// ServerTest.cpp where instance of sockClient is created
ServerTest::ServerTest(QObject *parent) : QObject(parent)
{
server = new QTcpServer( this );
}
void ServerTest::startServer()
{
connect( server, SIGNAL( newConnection() ), this, SLOT( incomingConnection() ) );
if( !server->listen( QHostAddress::Any, 9999) )
{
qDebug() << " Server failed to get started";
}
else
{
qDebug() << " Server started";
}
}
void ServerTest::stopServer()
{
server->close();
qDebug() << "Server closed";
}
ServerTest::~ServerTest()
{
server->close();
delete socketforClient;
delete server;
}
void ServerTest::incomingConnection()
{
socketforClient = new SockClient(this->parent(), server->nextPendingConnection() );
}
This is a very simple example:
qt.pro:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += classes.h
SOURCES += main.cpp
classes.h:
#include <QObject>
#include <QDebug>
class Agent_A : public QObject
{
Q_OBJECT
public slots:
void updateText(const QString &changeText) {
qDebug() << "updateText: " << changeText;
};
};
class SockClient : public QObject
{
Q_OBJECT
signals:
void updateTextinParent(const QString &text);
public:
void incomingText(const QString &text) {
emit updateTextinParent(text);
};
};
main.cpp:
#include "classes.h"
int main(int argc, char **argv) {
Agent_A *agent = new Agent_A;
SockClient client;
QObject::connect(&client, SIGNAL(updateTextinParent(const QString &)),
agent, SLOT(updateText(const QString &)));
client.incomingText(QString("hello"));
return 0;
}
Agent_A *agent = qobject_cast< Agent_A* >( this->parent() ); // ?? is this is right way to do..?
if( agent != NULL )
{
qDebug() << " we are in updateTextin" << changeText; // it never get printed so I assume instance is always nULL
agent->setLineEdit( chnageText );
}
Could you please check first that parent is not NULL?
And could you please show code where you create instance of SockClient?
Of course, you can't modify text because of you set as parent to socketClient object this pointer in Server_test class, so parent to socketClient will be Server_test but no Agent_A.
So make parent Agent_A for socketClient object:
socketforClient = new SockClient(this->parent(), server->nextPendingConnection());
Or you can make some others workarounds.
One more note: you make connection to newConnection() signal at your startServer method, not constructor. So if i start server, then stop them and start again server will be connected twice to signal and slot incomingConnection() will be called twice too. So you need disconnect at from signal at stopServer() method or do connection at constructor of class or use Qt::UniqueConnection.