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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值