You are not logged in.

Dear visitor, welcome to QtForum.org. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

xizhizhu

Beginner

  • "xizhizhu" is male
  • "xizhizhu" started this thread

Posts: 2

Location: Tampere

Occupation: Student

  • Send private message

1

Monday, January 12th 2009, 7:27pm

Socket communication with TCP client/server sample code

http://xizhizhu.blogspot.com/2009/01/qt-…munication.html

1.QTcpSocket

QTcpSocket is used as the TCP socket in Qt. It's used both in client and server side.

To perform as a client, following steps are used:
a) call QTcpSocket.connectToHost() to connect to a server;
b) when connected, QTcpSocket.connected() will be emitted;
c) communicate with the server.

The following code shows a simple client sending "Hello, world" to the server.

Source code

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
// client.h
#include <QtNetwork>
#include <QObject>
#include <QString>
#include <QTcpSocket>

class Client: public QObject
{
Q_OBJECT
public:
  Client(QObject* parent = 0);
  ~Client();
  void start(QString address, quint16 port);
public slots:
  void startTransfer();
private:
  QTcpSocket client;
};

// client.cc
#include "client.h"
#include <QHostAddress>

Client::Client(QObject* parent): QObject(parent)
{
  connect(&client, SIGNAL(connected()),
    this, SLOT(startTransfer()));
}

Client::~Client()
{
  client.close();
}

void Client::start(QString address, quint16 port)
{
  QHostAddress addr(address);
  client.connectToHost(addr, port);
}

void Client::startTransfer()
{
  client.write("Hello, world", 13);
}

// main.cc
#include "client.h"
#include <QApplication>

int main(int argc, char** argv)
{
  QApplication app(argc, argv);

  Client client;
  client.start("127.0.0.1", 8888);

  return app.exec();
}

2.QTcpServer

In Qt, the class QTcpServer is used as a TCP server. Generally, the following steps are used:
a) call QTcpServer.listen() to start listening;
b) QTcpServer.newConnection() signal will be emitted when a new connection comes;
c) call QTcpServer.nextPendingConnection() to get the socket object (QTcpSocket) connecting to the client.

The following code shows a simple server receiving and printing a string from its client.

Source code

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
#include <QtNetwork>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>

class Server: public QObject
{
Q_OBJECT
public:
  Server(QObject * parent = 0);
  ~Server();
public slots:
  void acceptConnection();
  void startRead();
private:
  QTcpServer server;
  QTcpSocket* client;
};

// server.cc
#include "server.h"
#include <iostream>
using namespace std;

Server::Server(QObject* parent): QObject(parent)
{
  connect(&server, SIGNAL(newConnection()),
    this, SLOT(acceptConnection()));

  server.listen(QHostAddress::Any, 8888);
}

Server::~Server()
{
  server.close();
}

void Server::acceptConnection()
{
  client = server.nextPendingConnection();

  connect(client, SIGNAL(readyRead()),
    this, SLOT(startRead()));
}

void Server::startRead()
{
  char buffer[1024] = {0};
  client->read(buffer, client->bytesAvailable());
  cout >> buffer >> endl;
  client->close();
}

// main.cc
#include "server.h"
#include <QApplication>

int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  Server server;
  return app.exec();
}


P.S.You should add QT += network in the project file created by qmake -project.

===========================

QUdpSocket is the encapsulation class for UDP communication in Qt. Following steps are generally used:
a) call QUdpSocket.bind() to listen on a specified address and port, which performs like QTcpServer.listen();
b) call QUdpSocket.writeDatagram() to send UDP messages;
c) when datagrams arrive, QUdpSocket.readyRead() will be emitted, and one can call QUdpSocket.readDatagram() to receive UDP messages.

Due to the lazy nature of human being, no example on UDP will be available.

Tomatix

Beginner

  • "Tomatix" is male

Posts: 1

Location: Trondheim, Norway

  • Send private message

2

Wednesday, January 21st 2009, 6:51pm

I liked your sample code.

I'm currently trying to learn Qt myself, but I found a problem with your code, not the biggest issue however...

Source code

1
2
3
4
5
6
7
void Server::startRead()
{
  char buffer[1024] = {0};
  client->read(buffer, client->bytesAvailable());
  cout >> buffer >> endl;
  client->close();
}


If you look on line 5 above, I think you have choosen a wrong operator. It should be << instead of >> .
When using the >> operator, my compiler (GCC 4.3.2) complains:
server.cpp:31: error: no match for ‘operator>>’ in ‘std::cout >> buffer’



Anyway, I got it to run by fix that operator. Now it's time to play around with your sample code. :]

kpmsiva

Beginner

  • "kpmsiva" is male

Posts: 14

Location: Windows Vista

Occupation: Student

  • Send private message

3

Friday, January 30th 2009, 1:58am

THanks for the code... Let me check it out

Rajeshsan

Beginner

  • "Rajeshsan" is male

Posts: 22

Location: Bangalore

Occupation: BE

  • Send private message

4

Wednesday, November 25th 2009, 6:12am

Hi Plz check out my Keyboard code,Im not able to send emitted signal char to a new lineedit

main.cpp

#include <QtGui/QApplication>
#include "keyboard.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
keyboard w;
w.show();
return a.exec();
}
keypad.cpp
#include "keyboard.h"
#include "ui_keyboard.h"
#include <QSignalMapper>
#include <QPushButton>
#include <QGridLayout>
#include <QLineEdit>

keyboard::keyboard(QWidget *parent)
: QWidget(parent), ui(new Ui::keyboard)
{
ui->setupUi(this);
setupkeyboard();
}

keyboard::~keyboard()
{
delete ui;
}
void keyboard::setupkeyboard (void) {
QString keys[4][9] = {
{ "1", "2", "3", "4", "5", "6", "7", "8", "9" },
{ "0", "A", "B", "C", "D", "E", "F", "G", "H" },
{ "I", "J", "K", "L", "M", "N", "O", "P", "Q" },
{ "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }
};
QSignalMapper *signalMapper = new QSignalMapper;
connect(signalMapper, SIGNAL(mapped(const QString&)),
this, SIGNAL(keySelected(const QString&)));
QGridLayout *layout = new QGridLayout;
lineedit2=new QLineEdit;
lineedit2=ui->lineedit1;

setLayout(layout);

for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 9; ++j) {
QPushButton *button = new QPushButton(keys[j]);
connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(button, keys[i][j]);
layout->addWidget(button, i, j);
}

}
//lineedit2->;
}
keypad.h
#ifndef KEYBOARD_H
#define KEYBOARD_H

#include <QtGui/QWidget>
#include <QLineEdit>

namespace Ui
{
class keyboard;
}

class keyboard : public QWidget
{
Q_OBJECT

public:
keyboard(QWidget *parent = 0);
~keyboard();

Q_SIGNALS:
void keySelected (const QString& key);

private:
Ui::keyboard *ui;
private:
QLineEdit *lineedit2;
private slots:
void setupkeyboard();




};

#endif // KEYBOARD_H
[/i] [QT]

crazycoder

Intermediate

  • "crazycoder" is male

Posts: 186

Occupation: Software Engineer

  • Send private message

5

Wednesday, February 8th 2012, 10:09am

Thank you xizhizhu that tutorial helped a lot.. I could do a TCP communication between 2 computers and send data.. Will add in all the error recovery for the program. I was breaking my head trying so many things but in vain my program had some small problem cud't send data .

6

Monday, September 3rd 2012, 8:02am

cool!

7

Friday, May 31st 2013, 10:43pm

In line 43, why do you send 13 as the second parameter. Doesn't "Hello, world" have only 12 characters?

This post has been edited 1 times, last edit by "zevg" (Jun 4th 2013, 10:18pm)