PDA

View Full Version : Qt Network Chat



Vivek1982
24th September 2013, 11:19
Dear All,

I'm new to Qt. I have installed Qt version 4.6.1 in my Windows PC. I need to develop a application, where I need to chat as well as I need to update some info in some Lineedits in my network connected PC. Initially I need to develop a simple chat window where I can send msgs to my peer PC. How this can be done.please support me..

Thanks in advance

Gokulnathvc
24th September 2013, 12:39
Kindly look at this : http://thesmithfam.org/blog/2009/07/09/example-qt-chat-program/

Vivek1982
25th September 2013, 05:14
thanks for fast reply.. I have gone thru the example.. Please can u suggest me code with simple comments or article. Where I can understand what is Socket programming in Qt. what are the procedures in code to be written in Prog to develop my own applications. It will be helpfull for me, If im getting any doc with how socket programming can be implemented in Qt.

wagmare
25th September 2013, 05:43
. Please can u suggest me code with simple comments or article. Where I can understand what is Socket programming in Qt
use these simple client/server program in qt
http://harmattan-dev.nokia.com/docs/library/html/qt4/network-fortuneserver.html
http://harmattan-dev.nokia.com/docs/library/html/qt4/network-fortuneclient.html
more simple than others for beginner ..

Vivek1982
26th September 2013, 05:20
Hi wagmare...

The site/link which u have sent is down. Its not accessible. Kindly suggest alternate way to get the same page or code.

wagmare
26th September 2013, 05:59
yeah me too .. yesterday it was working! .. some problem with the doc.trolltech server i guess ..
go to ur qt-assistant and search for
Fortune Server Example and Fortune Client Example

Vivek1982
26th September 2013, 09:24
Hi Wagmare..
Thanks for your reply. I have tried out a simple code where it sends simple qDebug msgs to compile output.I'm attaching code here.please go thru this and let me know.Im running a server code and client code at a time on same PC, my PC is connected to LAN(192.168.64.55). The moment I run client code. New connection is getting added and its printing qDebug msgs. please go thru the code. I feel problem may be at two points .one is at declaration socket QHostAddress and next is at main.cpp file where instead of default w.show(), listen()/connect to server().

TCPSERVER main.cpp
#include <QtGui/QApplication>
#include "server.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
server w;
//w.show();
w.listen();

return a.exec();
}


TCPSERVER server.cpp
#include "server.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <cstdio>

server::server(QWidget *parent)
: QMainWindow(parent)
{
server1 = new QTcpServer(this);
connect(server1, SIGNAL(newConnection()),
this, SLOT(on_newConnection()));
qDebug("new socket created");

}

server::~server()
{

}
void server::listen()
{
server1->listen(QHostAddress::LocalHost, 1234);
qDebug("Listening for new connection");

}
void server::on_newConnection()
{
socket = server1->nextPendingConnection();
qDebug("new connection established");
if(socket->state() == QTcpSocket::ConnectedState)
{
printf("New connection established.\n");
}
connect(socket, SIGNAL(disconnected()),
this, SLOT(on_disconnected()));
connect(socket, SIGNAL(readyRead()),
this, SLOT(on_readyRead()));
}
void server::on_readyRead()
{
while(socket->canReadLine())
{
QByteArray ba = socket->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
socket->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
}
}
void server::on_disconnected()
{
printf("Connection disconnected.\n");
disconnect(socket, SIGNAL(disconnected()));
disconnect(socket, SIGNAL(readyRead()));
socket->deleteLater();
}


TCPSERVER server.h
#ifndef SERVER_H
#define SERVER_H

#include <QtGui/QMainWindow>
#include <QObject>

class QTcpServer;
class QTcpSocket;

class server : public QMainWindow
{
Q_OBJECT

public:
server(QWidget *parent = 0);
void listen();
~server();
public slots:
void on_newConnection();
void on_readyRead();
void on_disconnected();

private:
QTcpServer *server1;
QTcpSocket *socket;
};

#endif // SERVER_H

Hi Wagmare..
Thanks for your reply. I have tried out a simple code where it sends simple qDebug msgs to compile output.I'm attaching code here.please go thru this and let me know.Im running a server code and client code at a time on same PC, my PC is connected to LAN(192.168.64.55). The moment I run client code. New connection is getting added and its printing qDebug msgs. please go thru the code. I feel problem may be at two points .one is at declaration socket QHostAddress and next is at main.cpp file where instead of default w.show(), listen()/connect to server().
TCPCLIENT main.cpp
#include <QtGui/QApplication>
#include "client.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
client w;
//w.show();
w.connectToserver();
return a.exec();
}


TCPCLIENT client.cpp

#include "client.h"
#include <QTcpSocket>
#include <QHostAddress>
#include <cstdio>


client::client(QWidget *parent)
: QMainWindow(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),
this, SLOT(on_connected()));
}

client::~client()
{

}
void client::connectToserver()
{
socket->connectToHost(QHostAddress::LocalHost, 1234);
qDebug("START PACKET SENDING");
}

void client::on_connected()
{
printf("Connection established.\n");
char buffer[1024];
forever
{
printf(">> ");
gets(buffer);
int len = strlen(buffer);
buffer[len] = '\n';
buffer[len+1] = '\0';
socket->write(buffer);
socket->flush();
}
}


TCPCLIENT client.h
#ifndef CLIENT_H
#define CLIENT_H

#include <QtGui/QMainWindow>
#include <QObject>

class QTcpSocket;

class client : public QMainWindow
{
Q_OBJECT

public:
client(QWidget *parent = 0);
void connectToserver();
~client();

private:
QTcpSocket *socket;
public slots:
void on_connected();

};

#endif // CLIENT_H

wagmare
26th September 2013, 10:27
sow ur .pro file .. did u added QT += network in it ..?

Vivek1982
26th September 2013, 12:26
Yes Wagmare. I have added initially only when creating the project. I'm posting the code of the Both files . I feel, problem may be the code or bcoz of I'm running on the LAN. I'm not sure of this. IP address QHostaddress also.
#-------------------------------------------------
#
# Project created by QtCreator 2013-09-25T13:28:55
#
#-------------------------------------------------

QT += network

TARGET = TcpServer
TEMPLATE = app


SOURCES += main.cpp\
server.cpp

HEADERS += server.h


#-------------------------------------------------
#
# Project created by QtCreator 2013-09-25T17:12:05
#
#-------------------------------------------------

QT += network

TARGET = TcpClient
TEMPLATE = app


SOURCES += main.cpp\
client.cpp

HEADERS += client.h

wagmare
26th September 2013, 12:41
for u

in .h


#include <QWidget>
#include <QLineEdit>
#include <QPushButton>

class QTcpSocket;

class TCPClient : public QWidget
{
Q_OBJECT

public:
TCPClient(QWidget *parent =0);


private slots:
void on_connected();
void connectToServer();
void writeMessage();


private:
QLineEdit *m_lineEdit;
QPushButton *m_button;
QPushButton *m_sendButton;
QTcpSocket *m_socket;
};


#include <QtGui>
#include <QTcpSocket>
#include <QHostAddress>
#include <QDebug>

#include "TCPClient.h"

TCPClient::TCPClient(QWidget *parent)
: QWidget(parent)
{
m_lineEdit = new QLineEdit();
m_button = new QPushButton("Connect");
m_sendButton = new QPushButton("Send");
m_sendButton->setEnabled(false);
connect(m_button,SIGNAL(clicked()), this,SLOT(connectToServer()));
connect(m_sendButton, SIGNAL(clicked()), this, SLOT(writeMessage()));
m_socket = new QTcpSocket;
connect(m_socket, SIGNAL(connected()), this, SLOT(on_connected()));

QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->addWidget(m_button);
hLayout->addWidget(m_sendButton);

QVBoxLayout *mLayout = new QVBoxLayout;
mLayout->addWidget(m_lineEdit);
mLayout->addLayout(hLayout);

this->setLayout(mLayout);
}

void
TCPClient::on_connected()
{
qDebug()<<"Debug Connection established:";
m_sendButton->setEnabled(true);


}

void
TCPClient::writeMessage()
{
QString writeData = this->m_lineEdit->text();

m_socket->write(writeData.toStdString().c_str());
m_socket->flush();
}


void
TCPClient::connectToServer()
{
m_socket->connectToHost(QHostAddress::LocalHost, 1234);

}


and main

#include <QApplication>

#include "TCPClient.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TCPClient c;

c.show();
return a.exec();
}

use this client ..

Vivek1982
27th September 2013, 03:58
Hi. wagmare.. Thanks for the code.. I will try in my PC and let you know the result. Any changes to made in TCP server.h/cpp/main.cpp or let that remain same as mentioned above discussions.

Thanks alot wagmare

wagmare
27th September 2013, 05:32
Any changes to made in TCP server.h/cpp/main.cpp or let that remain same as mentioned above discussions.
no changes required in server or main
but in client.cpp TCPClient::writeMessage() function im not converting QString to const char * properly ..
use
const char * data = writeData .toUtf8().constData();
to convert it properly .

Vivek1982
27th September 2013, 07:26
okay I will check it. Actually my few queries for you is. Please if possible answer.
1. In a network(Office LAN), can these two client and server program can run on same machine.
2. QHostaddress::Localhost this statement will call for IP address 127.0.0.1. how to use this.
3. In my PC IP address will taken automatically bcoz Im connected in office LAN.Any changes to be made...
4.Finally last query is on server side.. New connection found(), accept connection(), readyread(),write() delete()
clientside.. connecttoserver() writemsg(). these two type is enough..................

Any other general info required to Socket programming please let me know, where I can implement?

Added after 1 45 minutes:

Hi wagmare.. I have tried that example. As usual we have kept a qDebug msg in client program that is not executed. I didnt make any changes in the server directly. I started Server program next client program. GUI came no problem in that.but application window gave this msgs.
Client Application output
Starting C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe...
QMetaObject::connectSlotsByName: No matching signal for on_connected()
QAbstractSocket::connectToHost() called when already looking up or connecting/connected to "127.0.0.1"
QAbstractSocket::connectToHost() called when already looking up or connecting/connected to "127.0.0.1"
C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe exited with code 1
Starting C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe...
Cannot retrieve debugging output!
C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe exited with code 0
Starting C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe...
QMetaObject::connectSlotsByName: No matching signal for on_connected()
C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe exited with code 1
Starting C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe...
Cannot retrieve debugging output!
C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe exited with code 0
Starting C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe...
Cannot retrieve debugging output!
C:\Users\398292\Desktop\TCPClient\debug\TCPClient. exe exited with code 0

Vivek1982
27th September 2013, 11:14
HI wagmare.. I have tried enough times same sample code, what was shared by you. I had created full new project of TCPServer/Client. Still inmy LAN its not workin or in my same PC also. Any problem in the code. please review once, I need to understand where my code is going wrong.
TCP CLIENT main.cpp

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

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TCPClient w;
w.show();
return a.exec();
}

TCP Client.h

#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QTcpSocket>

class QTcpSocket;

namespace Ui {
class TCPClient;
}

class TCPClient : public QWidget {
Q_OBJECT
public:
TCPClient(QWidget *parent = 0);
~TCPClient();

protected:
void changeEvent(QEvent *e);

private:
Ui::TCPClient *ui;
QLineEdit *le;
QPushButton *pb_connect;
QPushButton *pb_send;
QTcpSocket *socket;

private slots:
void connecttoserver();
void on_connected();
void write();

};

#endif // TCPCLIENT_H

TCPClient.cpp


#include "tcpclient.h"
#include "ui_tcpclient.h"
#include <QtGui>
#include <QTcpSocket>
#include <QHostAddress>
#include <QDebug>


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

le= new QLineEdit;
le=ui->lineEdit;

pb_connect=new QPushButton;
pb_connect=ui->pushButton;
pb_connect->setText("CONNECT");
pb_connect->setEnabled(true);

pb_send=new QPushButton;
pb_send=ui->pushButton_2;
pb_send->setText("Send");
pb_send->setEnabled(false);

socket=new QTcpSocket(this);

connect(pb_connect,SIGNAL(clicked()),this,SLOT(con necttoserver()));
connect(pb_send,SIGNAL(clicked()),this,SLOT(write( )));
connect(socket,SIGNAL(connected()),this,SLOT(on_co nnected()));


}

TCPClient::~TCPClient()
{
delete ui;
}

void TCPClient::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}

void TCPClient::connecttoserver()
{
//QHostAddress hAddr;
// hAddr.setAddress("192.168.64.55");

socket->connectToHost(QHostAddress::Any,1234);


}

void TCPClient::on_connected()
{
pb_connect->setEnabled(false);
pb_send->setEnabled(true);
qDebug("Connection established");
}

void TCPClient::write()
{
QString data=this->le->text();
socket->write(data.toUtf8().constData());
//const char * data = writeData .toUtf8().constData();

socket->flush();
}


TCP Client.pro
#-------------------------------------------------
#
# Project created by QtCreator 2013-09-27T10:57:57
#
#-------------------------------------------------

QT += network

TARGET = TCPClient
TEMPLATE = app


SOURCES += main.cpp\
tcpclient.cpp

HEADERS += tcpclient.h

FORMS += tcpclient.ui

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

TCP Server.main.cpp


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

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Tcpserver w;
w.listen();
w.show();
return a.exec();
}


TCP SERVER.h


#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QTcpServer>
#include <QTcpSocket>

class QTcpServer;
class QTcpSocket;

namespace Ui {
class Tcpserver;
}

class Tcpserver : public QWidget {
Q_OBJECT
public:
Tcpserver(QWidget *parent = 0);
~Tcpserver();
void listen();

protected:
void changeEvent(QEvent *e);

private:
Ui::Tcpserver *ui;
QLineEdit *le;
QPushButton *Pb_newconn;
QPushButton *Pb_send;
QTcpServer *server;
QTcpSocket *socket;

private slots:

void on_newconn();
void read_socket();
void socket_disconnected();

};


#endif // TCPSERVER_H

TCP SERVER.cpp


#include "tcpserver.h"
#include "ui_tcpserver.h"

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

le=new QLineEdit;
le=ui->lineEdit;

Pb_newconn= new QPushButton;
Pb_newconn=ui->pushButton;
Pb_newconn->setText("Listen");
Pb_newconn->setEnabled(true);

Pb_send=new QPushButton;
Pb_send=ui->pushButton_2;
Pb_send->setText("SEND");
Pb_send->setEnabled(false);

server=new QTcpServer(this);

socket= new QTcpSocket(this);

//connect(Pb_newconn,SIGNAL(clicked()),this,SLOT(lis ten()));
connect(server,SIGNAL(newConnection()),this,SLOT(o n_newconn()));
connect(socket,SIGNAL(readyRead()),this,SLOT(read_ socket()));
connect(socket,SIGNAL(disconnected()),this,SLOT(so cket_disconnected()));
}

Tcpserver::~Tcpserver()
{
delete ui;
}

void Tcpserver::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}

void Tcpserver::listen()
{
//QHostAddress hAddr;
//hAddr.setAddress("192.168.64.52");
server->listen(QHostAddress::Any,1234);
qDebug("Listening to new connection");
}
void Tcpserver::on_newconn()
{
socket=server->nextPendingConnection();
if(socket->state()==QTcpSocket::ConnectedState)
{
qDebug("new connection established");
}
Pb_newconn->setEnabled(false);
Pb_send->setEnabled(true);
}
void Tcpserver::read_socket()
{
while(socket->canReadLine())
{
QByteArray buffer= socket->readLine();
if(strcmp(buffer.constData(), "!exit\n") == 0)
{
qDebug("No data");
}
else
le->setText(buffer);

}

}
void Tcpserver::socket_disconnected()
{
qDebug("Socket Disconnected");
socket->deleteLater();
}


TCP SERVER.pro
#-------------------------------------------------
#
# Project created by QtCreator 2013-09-27T13:50:57
#
#-------------------------------------------------

QT += network

TARGET = TCPServer
TEMPLATE = app


SOURCES += main.cpp\
tcpserver.cpp

HEADERS += tcpserver.h

FORMS += tcpserver.ui

toufic.dbouk
27th September 2013, 23:15
@Vivek1982 use code tags please for better reading and viewing.

Vivek1982
30th September 2013, 05:05
Hi.. Toufic.dbouk.. Thanks for reply and giving idea of using Quotes. I was not knowing how to use it.. .

I have gone thru the page of BB code. I start posting comments/discussions/code in the right way.... thanks

Added after 14 minutes:

Hi Wagmare. thanks for all your suggestions and comments. I have created now chatting window on my PC. The problem earlier was data conversion and calling the functions at proper procedure. I had kept lot Qdebug msgs then, i got to know wat was the error. now I have created simple chat window in server/client GUI. In my PC if I'm running both server/client applications I can chat. If I run server in one and client in two different PC. I'm not getting it. Any issues in the QHostAddress::... How to use class in LAN connected PCs..

Thanks in Advance

wagmare
30th September 2013, 08:32
be sure with these things

address is ur server address and port ur valid server port no

QHostAddress addr(address);
bool rval = client.reset();
qDebug() << "Reset before Connect to Host = " << rval;
socket.connectToHost(address, port);

Vivek1982
30th September 2013, 10:12
Hi Wagmare.. I was able to communicate between two PCs connected in LAN. In client I had mentioned

void TCPClient::connecttoserver()
{
QHostAddress hAddr;
hAddr.setAddress("192.168.64.55");
socket->connectToHost(hAddr,1234);
// socket->connectToHost("192.168.64.52",1234);
}

In server I had mentioned these lines.

void Tcpserver::listen()
{
server->listen(QHostAddress::Any,1234);
qDebug("Listening to new connection");
}

After compiling by these changes I was able to do chatting in LAN between two PCs server/client applications.
Now, I need to have chat application and sending commands{encrypted codes} in the same socket. I was trying to create new socket and implement it in the same code but it was not possible. I wrote two sockets in both client/server application. program server application was hanging on PC, suggested to close bcoz of listening/connecting two times to the server.

How to address this issue.Whether two or more sockets can be connected to same server to send different datas Or any tagging should be done before writing into socket such while decoding at remote end it will classify this info for whom.. means lineEdit1(chatting msg) or for LineEdit2(commands)..


Thanks in advance.

Vivek1982
1st October 2013, 06:03
Hi.. I need to create a program for chatting and another lineedit to send specific commands, how it can be either by creating socket or tagging prior sending in same socket. please suggest in this, which is better. how it can addressed....

Thanks in advance

Added after 52 minutes:

Hi.. wagmare any suggestion from you to how to address this...