Developing applications that used to communicate with other computer over the network is an interesting area in the filed of programming. With the introduction of QT C++ libraries , this task become less complicated compared to the network programming in the past . All you need to know is the basics of TCP/IP and how computers communicate over the network using TCP/IP protocol.
In this programming video tutorial , we will show you how to develop a basic Networking applications based on TCP/IP Library QTcpServer and QTcpSocket .
Watch the YouTube Video From the link below..
Main Source Code
Client Part
Dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include < QTcpSocket >
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
QTcpSocket *m_pClientsocket;
private slots:
void displayError ( QAbstractSocket::SocketError socketError );
private slots:
void on_pushButtonConnect_clicked();
void on_pushButtonSend_clicked();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
Dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
m_pClientsocket = new QTcpSocket(this);
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButtonConnect_clicked()
{
m_pClientsocket->connectToHost(ui->textEditIP->toPlainText(),quint16(ui->textEditPort->toPlainText().toInt()) );
connect(m_pClientsocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
void Dialog::on_pushButtonSend_clicked()
{
QString message = ui->textEditMesage->toPlainText().trimmed();
// Only send the text to the chat server if it's not empty:
if(!message.isEmpty())
{
m_pClientsocket->write(QString(message + "
").toUtf8());
}
// Clear out the input box so they can type something else:
ui->textEditMesage->clear();
// Put the focus back into the input box so they can type again:
ui->textEditMesage->setFocus();
}
void Dialog::displayError ( QAbstractSocket::SocketError socketError )
{
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
QMessageBox::information(this, tr("Fortune Client"),
tr("The host was not found. Please check the "
"host name and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
QMessageBox::information(this, tr("Fortune Client"),
tr("The connection was refused by the peer. "
"Make sure the fortune server is running, "
"and check that the host name and port "
"settings are correct."));
break;
default:
QMessageBox::information(this, tr("Fortune Client"),
tr("The following error occurred: %1.")
.arg(m_pClientsocket->errorString()));
}
}
main.cpp
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
Server Part
HelloWorldServer .h
#ifndef HELLOWORLDSERVER_H
#define HELLOWORLDSERVER_H
#include <QTcpServer>
#include "MainWindow.h"
class MainWindow;
class HelloWorldServer : public QTcpServer
{
public:
Q_OBJECT
public:
HelloWorldServer(MainWindow* pHelloServer,QObject *parent=0);
MainWindow* m_pHelloWindow;
private slots:
void readyRead();
void disconnected();
protected:
void incomingConnection(int socketfd);
private:
QSet<QTcpSocket*> clients;
};
#endif // HELLOWORLDSERVER_H
HelloWorldServer.cpp
#include "helloworldserver.h"
#include <QTcpSocket>
HelloWorldServer::HelloWorldServer(MainWindow* pHelloServer,QObject *parent) : QTcpServer(parent)
{
m_pHelloWindow=pHelloServer;
}
void HelloWorldServer::incomingConnection(int socketfd)
{
QTcpSocket *client = new QTcpSocket(this);
client->setSocketDescriptor(socketfd);
clients.insert(client);
m_pHelloWindow->addMessage("New client from: "+client->peerAddress().toString());
connect(client, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));
}
void HelloWorldServer::readyRead()
{
QTcpSocket *client = (QTcpSocket*)sender();
while(client->canReadLine())
{
QString line = QString::fromUtf8(client->readLine()).trimmed();
//qDebug() << "Read line:" << line;
m_pHelloWindow->addMessage(line);
}
}
void HelloWorldServer::disconnected()
{
QTcpSocket *client = (QTcpSocket*)sender();
qDebug() << "Client disconnected:" << client->peerAddress().toString();
clients.remove(client);
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "HelloWorldServer.h"
namespace Ui {
class MainWindow;
}
class HelloWorldServer;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void addMessage(QString Msg);
HelloWorldServer* m_pBoxServer;
private slots:
void on_pushButtonStart_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButtonStart_clicked()
{
m_pBoxServer= new HelloWorldServer(this);
bool success = m_pBoxServer->listen(QHostAddress::Any, quint16(ui->textEditPort->toPlainText().toInt()));
if(!success)
{
addMessage("Server failed...");
}
else
{
addMessage("Server Started...");
}
}
void MainWindow::addMessage(QString Msg)
{
ui->textEditStatus->setText(Msg);
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}