IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau Discussion :

[QTcpSocket / QTcpServer] Communication bidirectionnelle


Sujet :

Réseau

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre chevronné Avatar de Jbx 2.0b
    Homme Profil pro
    Développeur C++/3D
    Inscrit en
    Septembre 2002
    Messages
    477
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur C++/3D
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2002
    Messages : 477
    Par défaut [QTcpSocket / QTcpServer] Communication bidirectionnelle
    Bonjour,

    Je suis en train de développer un petit programme basé sur QTcpSocket et QTcpServer, le but étant d'avoir une communication bidirectionnelle entre un serveur et un client.
    Malheureusement, si je reçois les données correctement au niveau du client la communication client => serveur ne fonctionne pas.
    N'étant pas du tout familier avec les sockets, Qt ou autre, j'en profite pour poster l'ensemble de mon code pour que vous puissiez faire des éventuelles critiques.

    Voici le code coté serveur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    #include "CTcpServer.h"
     
    #include <QFile>
    #include <QCoreApplication>
     
    //-------------------------------------------------------------------------------------------------
    CTcpServer::CTcpServer(int iListenPort, QObject *parent /*= 0*/)
    : QTcpServer(parent)
    , m_iListenPort(iListenPort)
    , m_bIsRunning(false)
    , m_iBlockSize(0)
    {
    	connect(this, SIGNAL(newConnection()), this, SLOT(onServerConnection()));
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::stop()
    {
    	m_bIsRunning = false;
     
    	close();
     
    	foreach (QTcpSocket* tcpSocket, m_TcpSocketList)
    	{
    		tcpSocket->close();
    	}
     
    	m_TcpSocketList.clear();
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::addSendMessage(const QString& strMessage)
    {
    	m_strSendMessage = strMessage;
    	sendMessage();
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::startListening()
    {
    	if (!listen(QHostAddress::Any, m_iListenPort))
    	{
    		qDebug() << "Unable to start the server";
    		m_bIsRunning = false;
    	}
    	else
    	{
    		m_bIsRunning = true;
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::sendMessage()
    {
    	if (m_bIsRunning && !m_strSendMessage.isEmpty())
    	{
    		foreach (QTcpSocket* tcpSocket, m_TcpSocketList)
    		{
    			QByteArray block;
    			QDataStream out(&block, QIODevice::WriteOnly);
    			out.setVersion(QDataStream::Qt_4_7);
    			out << (quint16)0;
    			out << m_strSendMessage;
    			out.device()->seek(0);
    			out << (quint16)(block.size() - sizeof(quint16));
     
    			tcpSocket->write(block);
    			tcpSocket->waitForBytesWritten();
    		}
     
    		m_strSendMessage.clear();
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onServerConnection()
    {
    	QTcpSocket* pSocket = nextPendingConnection();
    	//pSocket->setReadBufferSize(SOCKET_READ_BUFFER);
    	m_TcpSocketList.append(pSocket);
    	connect(pSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
    	connect(pSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onSocketReadyRead()
    {
    	if (QTcpSocket* pSocket = dynamic_cast<QTcpSocket*>(QObject::sender()))
    	{
    		QDataStream in(pSocket);
    		in.setVersion(QDataStream::Qt_4_7);
     
    		if (m_iBlockSize == 0)
    		{
    			if (pSocket->bytesAvailable() < (int)sizeof(quint16))
    				return;
     
    			in >> m_iBlockSize;
    		}
     
    		if (pSocket->bytesAvailable() < m_iBlockSize)
    			return;
     
    		m_iBlockSize = 0;
     
    		// On arrive jamais ici.. :(
    		QString lastMsg;
    		in >> lastMsg;
    		emit newMessage(pSocket->peerAddress().toString(), lastMsg);
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onDisconnected()
    {
    	if (QTcpSocket* pSocket = dynamic_cast<QTcpSocket*>(QObject::sender()))
    	{
    		m_TcpSocketList.removeAll(pSocket);
    	}
    }
    Et le côté client :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
     
    #include <QtGui>
    #include <QtNetwork>
     
    #include "client.h"
     
    //-------------------------------------------------------------------------------------------------
    Client::Client(const QString& strHostIPAdress, int iPort, QObject *parent /*= 0*/)
    : QObject(parent)
    , m_strHostIPAdress(strHostIPAdress)
    , m_iPort(iPort)
    , m_bIsConnected(false)
    , m_iBlockSize(0)
    {
    	m_TcpSocket = new QTcpSocket(this);
     
    	connect(m_TcpSocket, SIGNAL(readyRead()), this, SLOT(onReadMessage()));
    	connect(m_TcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
    	connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(disconnectFromHost()));
     
    	connect(&m_RetryConnectionTimer, SIGNAL(timeout()), this, SLOT(connectToHost()));
    	connectToHost();
     
    	m_RetryConnectionTimer.start(iDTReconnection);
    }
     
    //-------------------------------------------------------------------------------------------------
    Client::~Client()
    {
    	delete m_TcpSocket;
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::connectToHost()
    {
    	if (!m_bIsConnected)
    	{
    		m_bIsConnected = true;
    		m_iBlockSize = 0;
    		m_TcpSocket->abort();
    		m_TcpSocket->connectToHost(m_strHostIPAdress, m_iPort, QIODevice::ReadWrite);
    		m_TcpSocket->waitForConnected();
     
    		qDebug() << "Client::connectToHost() : Connected.";
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::disconnectFromHost()
    {
    	m_bIsConnected = false;
    	m_RetryConnectionTimer.stop();
    	m_TcpSocket->abort();
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onReadMessage()
    {
    	QDataStream in(m_TcpSocket);
    	in.setVersion(QDataStream::Qt_4_7);
     
    	if (m_iBlockSize == 0)
    	{
    		if (m_TcpSocket->bytesAvailable() < (int)sizeof(quint16))
    			return;
     
    		in >> m_iBlockSize;
    	}
     
    	if (m_TcpSocket->bytesAvailable() < m_iBlockSize)
    		return;
     
    	m_iBlockSize = 0;
     
    	QString lastMsg;
    	in >> lastMsg;
    	emit newMessage(lastMsg);
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onSocketError(QAbstractSocket::SocketError socketError)
    {
    	m_bIsConnected = false;
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::addSendMessage(const QString& sendMessage)
    {
    	if (m_bIsConnected && !sendMessage.isEmpty())
    	{
    		QByteArray packet;  
    		QDataStream out(&packet, QIODevice::WriteOnly);
    		out.setVersion(QDataStream::Qt_4_7);
    		out << (quint16)0;
    		out << sendMessage;
    		out.device()->seek(0);  
    		out << (quint16)(packet.size() - sizeof(quint16));  
    		m_TcpSocket->write(packet);
    		m_TcpSocket->flush();
    		m_TcpSocket->waitForBytesWritten();		
    	}
    }

  2. #2
    yan
    yan est déconnecté
    Rédacteur
    Avatar de yan
    Homme Profil pro
    Ingénieur expert
    Inscrit en
    Mars 2004
    Messages
    10 035
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur expert
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2004
    Messages : 10 035
    Par défaut
    Salut.
    Ton client et ton serveur sont sur la même machine? Si non, sur le même os?
    arrive tu à faire du pas à pas ?

  3. #3
    Membre chevronné Avatar de Jbx 2.0b
    Homme Profil pro
    Développeur C++/3D
    Inscrit en
    Septembre 2002
    Messages
    477
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur C++/3D
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2002
    Messages : 477
    Par défaut
    Bonjour,

    Oui, actuellement ils sont sur la même machine et le même OS (win7). Le port utilisé est 54321.
    Je peux faire du pas à pas (je suis sous VS2008). Par exemple tcpSocket->write() me renvoi bien le nombre d’octet écrit autant sur le client que le serveur.

    J'ai l'impression donc que le soucis viendrait de onSocketReadyRead().

    En particulier ici :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    if (m_iBlockSize == 0)
    {
    	if (pSocket->bytesAvailable() < (int)sizeof(quint16))
    		return;
     
    	in >> m_iBlockSize;
    }
     
    if (pSocket->bytesAvailable() < m_iBlockSize)
    	return; // <= on sort toujours ici
    Ce qui m'étonne, c'est que côté client, le même code exactement fonctionne.

  4. #4
    yan
    yan est déconnecté
    Rédacteur
    Avatar de yan
    Homme Profil pro
    Ingénieur expert
    Inscrit en
    Mars 2004
    Messages
    10 035
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur expert
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2004
    Messages : 10 035
    Par défaut
    la valeur m_iBlockSize est correcte?

    Peux tu faire un exemple compilable?

  5. #5
    Membre chevronné Avatar de Jbx 2.0b
    Homme Profil pro
    Développeur C++/3D
    Inscrit en
    Septembre 2002
    Messages
    477
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur C++/3D
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2002
    Messages : 477
    Par défaut
    Elle a bien une valeur, mais elle ne semble pas correcte.
    Voici l'ensemble de mon code si tu veux tester:

    SERVEUR

    main.cpp :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    #include <QApplication>
    #include "CTcpServer.h"
     
     int main(int argc, char *argv[])
     {
         QApplication app(argc, argv);
         CTcpServer server(54321);
         server.startListening();
         return app.exec();
     }
    CTcpServer.h :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
     
    #ifndef CTCPSERVER_H
    #define CTCPSERVER_H
     
    #include <QTcpServer>
    #include <QList>
     
    class CTcpServer : public QTcpServer
    {
    	Q_OBJECT
     
    public:
     
    	CTcpServer(int iListenPort, QObject *parent = 0);
     
    	void startListening();
     
    	bool addFile(const QString& fileName);
    	void addSendMessage(const QString& strMessage);
     
    signals:
     
    	void newMessage(const QString& strIP, const QString& strMessage);
     
    public slots:
     
    	void stop();
     
    protected slots:
     
    	void onTimeout();
    	void onServerConnection();
    	void onSocketReadyRead();
    	void onDisconnected();
     
    protected:
     
    	void sendMessage();
     
    	QString m_strSendMessage;
    	int m_iListenPort;
    	QList<QTcpSocket*> m_TcpSocketList;
    	bool m_bIsRunning;
    	void updateThreadMessage();
    	int m_iBlockSize;
    };
     
    #endif // CTCPSERVER_H
    CTcpServeur.cpp :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
     
    #include "CTcpServer.h"
     
    #include <QFile>
    #include <QCoreApplication>
    #include <QTimer>
     
    //-------------------------------------------------------------------------------------------------
    CTcpServer::CTcpServer(int iListenPort, QObject *parent /*= 0*/)
    : QTcpServer(parent)
    , m_iListenPort(iListenPort)
    , m_bIsRunning(false)
    , m_iBlockSize(0)
    {
    	connect(this, SIGNAL(newConnection()), this, SLOT(onServerConnection()));
    	QTimer *timer = new QTimer();
    	connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    	timer->start(1000);
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onTimeout()
    {
    	addSendMessage("Blabla");
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::stop()
    {
    	m_bIsRunning = false;
     
    	close();
     
    	foreach (QTcpSocket* tcpSocket, m_TcpSocketList)
    	{
    		tcpSocket->close();
    	}
     
    	m_TcpSocketList.clear();
    }
     
    //-------------------------------------------------------------------------------------------------
    bool CTcpServer::addFile(const QString& fileName)
    {
    	QFile file(fileName);
    	if (!file.open(QIODevice::ReadOnly))
    	{
    		return false;
    	}
    	QTextStream in(&file);
    	while (!in.atEnd())
    	{
    		m_strSendMessage += in.readLine();
    	}
     
    	file.close();
     
    	sendMessage();
     
    	return true;
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::addSendMessage(const QString& strMessage)
    {
    	m_strSendMessage = strMessage;
    	sendMessage();
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::startListening()
    {
    	if (!listen(QHostAddress::Any, m_iListenPort))
    	{
    		qDebug() << "Unable to start the server";
    		m_bIsRunning = false;
    	}
    	else
    	{
    		m_bIsRunning = true;
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::sendMessage()
    {
    	if (m_bIsRunning && !m_strSendMessage.isEmpty())
    	{
    		foreach (QTcpSocket* tcpSocket, m_TcpSocketList)
    		{
    			QByteArray packet;  
    			QDataStream out(&packet, QIODevice::WriteOnly);
    			out.setVersion(QDataStream::Qt_4_7);
    			out << (quint16)0;
    			out << m_strSendMessage;
    			out.device()->seek(0);  
    			out << (quint16)(packet.size() - sizeof(quint16));  
    			tcpSocket->write(packet);
    			tcpSocket->waitForBytesWritten();		
    		}
     
    		m_strSendMessage.clear();
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onServerConnection()
    {
    	QTcpSocket* pSocket = nextPendingConnection();
    	m_TcpSocketList.append(pSocket);
    	connect(pSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
    	connect(pSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onSocketReadyRead()
    {
    	if (QTcpSocket* pSocket = dynamic_cast<QTcpSocket*>(QObject::sender()))
    	{
    		QDataStream in(pSocket);
    		in.setVersion(QDataStream::Qt_4_7);
     
    		if (m_iBlockSize == 0)
    		{
    			if (pSocket->bytesAvailable() < (int)sizeof(quint16))
    				return;
     
    			in >> m_iBlockSize;
    		}
     
    		if (pSocket->bytesAvailable() < m_iBlockSize)
    			return;
     
    		m_iBlockSize = 0;
     
    		// On arrive jamais ici.. :(
    		QString lastMsg;
    		in >> lastMsg;
    		qDebug() << lastMsg;
    		emit newMessage(pSocket->peerAddress().toString(), lastMsg);
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void CTcpServer::onDisconnected()
    {
    	if (QTcpSocket* pSocket = dynamic_cast<QTcpSocket*>(QObject::sender()))
    	{
    		m_TcpSocketList.removeAll(pSocket);
    	}
    }

    CLIENT

    main.cpp :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <QApplication>
    #include "client.h"
     
     int main(int argc, char *argv[])
     {
         QApplication app(argc, argv);
         Client client("10.1.0.50", 54321);
         return app.exec();
     }

    client.h :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
     
    #ifndef CLIENT_H
    #define CLIENT_H
     
    #include <QTcpSocket>
    #include <QTimer>
     
    class Client : public QObject
    {
    	Q_OBJECT
     
    public:
     
    	Client(const QString& strHostIPAdress, int iPort, QObject *parent = 0);
     
    	virtual ~Client();
     
    	void addSendMessage(const QString& sendMessage);
     
    signals:
     
    	void newMessage(const QString& strMessage);
     
    public slots:
     
    	void connectToHost();
    	void disconnect();
     
    protected slots:
     
    	void onSocketReadyRead();
    	void onSocketError(QAbstractSocket::SocketError socketError);
    	void onDisconnectedFromHost();
    	void onConnectedToHost();
    	void onTimeout();
     
    protected:
     
    	static const int iDTReconnection = 5000;
     
    	bool m_bIsConnected;
    	QTimer m_RetryConnectionTimer;
    	QTcpSocket *m_TcpSocket;
    	quint16 m_iBlockSize;
    	int m_iPort;
    	QString m_strHostIPAdress;
    };
     
    #endif
    client.cpp :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
     
    #include <QtNetwork>
     
    #include "client.h"
     
    //-------------------------------------------------------------------------------------------------
    Client::Client(const QString& strHostIPAdress, int iPort, QObject *parent /*= 0*/)
    : QObject(parent)
    , m_strHostIPAdress(strHostIPAdress)
    , m_iPort(iPort)
    , m_bIsConnected(false)
    , m_iBlockSize(0)
    {
    	m_TcpSocket = new QTcpSocket(this);
     
    	connect(m_TcpSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
    	connect(m_TcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
    	connect(m_TcpSocket, SIGNAL(connected()), this, SLOT(onConnectedToHost()));
    	connect(m_TcpSocket, SIGNAL(disconnected()), this, SLOT(onDisconnectedFromHost()));
     
    	connect(&m_RetryConnectionTimer, SIGNAL(timeout()), this, SLOT(connectToHost()));
    	connectToHost();
     
    	m_RetryConnectionTimer.start(iDTReconnection);
     
    	QTimer *timer = new QTimer();
    	connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    	timer->start(1000);
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onTimeout()
    {
    	addSendMessage("Blabla");
    }
     
    //-------------------------------------------------------------------------------------------------
    Client::~Client()
    {
    	delete m_TcpSocket;
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::connectToHost()
    {
    	if (!m_bIsConnected)
    	{
    		m_iBlockSize = 0;
    		m_TcpSocket->connectToHost(m_strHostIPAdress, m_iPort, QIODevice::ReadWrite);
    		m_TcpSocket->waitForConnected();
    	}
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onConnectedToHost()
    {
    	m_bIsConnected = true;
    	qDebug() << "Client::connectToHost() : Connected.";
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::disconnect()
    {
    	m_TcpSocket->disconnectFromHost();
    	m_RetryConnectionTimer.stop();
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onDisconnectedFromHost()
    {
    	m_bIsConnected = false;
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onSocketReadyRead()
    {
    	QDataStream in(m_TcpSocket);
    	in.setVersion(QDataStream::Qt_4_7);
     
    	if (m_iBlockSize == 0)
    	{
    		if (m_TcpSocket->bytesAvailable() < (int)sizeof(quint16))
    			return;
     
    		in >> m_iBlockSize;
    	}
     
    	if (m_TcpSocket->bytesAvailable() < m_iBlockSize)
    		return;
     
    	m_iBlockSize = 0;
     
    	QString lastMsg;
    	in >> lastMsg;
     
    	qDebug() << lastMsg;
    	emit newMessage(lastMsg);
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::onSocketError(QAbstractSocket::SocketError socketError)
    {
    	m_bIsConnected = false;
    }
     
    //-------------------------------------------------------------------------------------------------
    void Client::addSendMessage(const QString& sendMessage)
    {
    	if (m_bIsConnected && !sendMessage.isEmpty())
    	{
    		QByteArray packet;  
    		QDataStream out(&packet, QIODevice::WriteOnly);
    		out.setVersion(QDataStream::Qt_4_7);
    		out << (quint16)0;
    		out << sendMessage;
    		out.device()->seek(0);  
    		out << (quint16)(packet.size() - sizeof(quint16));  
    		m_TcpSocket->write(packet);
    		m_TcpSocket->waitForBytesWritten();		
    	}
    }
    EDIT : suppression de pSocket->setReadBufferSize(10000); que j'avais mit uniquement pour un test.

  6. #6
    yan
    yan est déconnecté
    Rédacteur
    Avatar de yan
    Homme Profil pro
    Ingénieur expert
    Inscrit en
    Mars 2004
    Messages
    10 035
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Ingénieur expert
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2004
    Messages : 10 035
    Par défaut
    Elle a bien une valeur, mais elle ne semble pas correcte.
    On ne sais jamais, mais verifie le byteOrder de tes QDAtaStream.
    http://qt-project.org/doc/qt-4.8/qda...html#byteOrder

    Es ce que tu pourrais faire un zip de ces code sources? Se sera plus simple pour les tester.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. communication bidirectionnel entre le serveur et l'application
    Par Nono1nd dans le forum API standards et tierces
    Réponses: 11
    Dernier message: 11/03/2014, 04h43
  2. Communication bidirectionnelle entre 2 postes distants par Socket
    Par tails dans le forum API standards et tierces
    Réponses: 5
    Dernier message: 05/07/2013, 16h42
  3. QTcpSocket : problème de communication avec hardware
    Par franchouze dans le forum Débuter
    Réponses: 1
    Dernier message: 19/10/2011, 14h32
  4. communication bidirectionnels ?
    Par Edw@rd dans le forum POSIX
    Réponses: 4
    Dernier message: 30/11/2010, 16h02
  5. Réponses: 2
    Dernier message: 21/08/2009, 16h18

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo