QT开发应用程序(16)-- TCP通讯实例

1、TCP Server端

#include <QTcpServer>
#include <QObject>
#include "Myclientsocket.h"

class MyServer : public QTcpServer
{
    Q_OBJECT
public:
    MyServer (QObject *parent=0,int port=0);
    QList<MyClientsocket*> myClientSocketList;
signals:
    void updateServer(QString,int);
public slots:
    void updateClients(QString,int);
    void slotDisconnected(int);
protected:
    void incomingConnection(int socketDescriptor);
};

CPP 源文件

#include "MyServer .h"

MyServer ::MyServer (QObject *parent,int port)
    :QTcpServer(parent)
{
    listen(QHostAddress::Any,port);
}

void MyServer ::incomingConnection(int socketDescriptor)
{
    MyClientsocket* ClientSocket=new MyClientsocket(this);
    connect(ClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));
    connect(ClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));

    ClientSocket->setSocketDescriptor(socketDescriptor);

    myClientSocketList.append(ClientSocket);
}

void MyServer::updateClients(QString msg,int length)
{
    emit updateServer(msg,length);
    for(int i=0;i<myClientSocketList.count();i++)
    {
        QTcpSocket *item = myClientSocketList.at(i);
        if(item->write(msg.toLatin1(),length)!=length)
        {
            continue;
        }
    }
}

void MyServer ::slotDisconnected(int descriptor)
{
    for(int i=0;i<myClientSocketList.count();i++)
    {
        QTcpSocket *item = myClientSocketList.at(i);
        if(item->socketDescriptor()==descriptor)
        {
            myClientSocketList.removeAt(i);
            return;
        }
    }
    return;
}

2、TCP Client端

#include <QTcpSocket>
#include <QObject>

class MyClientSocket : public QTcpSocket
{
    Q_OBJECT
public:
    MyClientSocket (QObject *parent=0);
signals:
    void updateClients(QString,int);
    void disconnected(int);
protected slots:
    void dataReceived();
    void slotDisconnected();
};

CPP 源文件

#include "MyClientSocket .h"

MyClientSocket ::MyClientSocket (QObject *parent)
{
    connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));
    connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
}

void MyClientSocket ::dataReceived()
{
    while(bytesAvailable()>0)
    {
        int length = bytesAvailable();
        char buf[1024];
        read(buf,length);

        QString msg=buf;
        emit updateClients(msg,length);
    }
}

void MyClientSocket ::slotDisconnected()
{
    emit disconnected(this->socketDescriptor());
}
发布了30 篇原创文章 · 获赞 9 · 访问量 925

猜你喜欢

转载自blog.csdn.net/x879014419/article/details/105144932
今日推荐