30 Mart 2017 Perşembe

QT- QTCP SERVER

main.cpp

#include < QCoreApplication>
#include< myserver.h>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    MyServer mServer;
    return a.exec();
}


---------------------------------
myserver.h


#ifndef MYSERVER_H
#define MYSERVER_H
#include < QObject>
#include< QDebug>
#include< QTcpServer>
#include< QTcpSocket>
class MyServer : public QObject
{
    Q_OBJECT
public:
    explicit MyServer(QObject *parent = 0);

signals:
public slots:
    void newConnection();

private:
    QTcpServer *server;
};

#endif // MYSERVER_H
---------------------------------------------------
myserver.cpp

#include " myserver.h"
MyServer::MyServer(QObject *parent) : QObject(parent)
{
   server = new QTcpServer(this);
   connect(server,SIGNAL(newConnection()),this,SLOT(newConnection()));
   if(!server->listen(QHostAddress::Any,1234))
   {
       qDebug() < <    "Server Could Not Star! ";
   }
   else
   {
       qDebug() < <    "Server Started ";
   }
}
void MyServer::newConnection()
{
    QTcpSocket *socket  =  server->nextPendingConnection();
    socket->write("Hello Client \r\n");
    socket->flush();
    socket->waitForBytesWritten(3000);
    socket->close();
}


Share: