当前位置: 代码迷 >> QT开发 >> 初学QT的TCP编程,有几点不明白。该如何处理
  详细解决方案

初学QT的TCP编程,有几点不明白。该如何处理

热度:90   发布时间:2016-04-25 04:15:36.0
初学QT的TCP编程,有几点不明白。。
我是完全复制书上的程序的,虽然能运行成功了,但是代码中有几个地方不明白。。求求解。。
我不知道该怎么表达我想问的问题,只好把所有的程序粘贴出来,然后加些注释。。。
程序如下:

#ifndef SERVER_H
#define SERVER_H

#include <QtNetwork>
#include "tcpclientsocket.h"
class Server : public QTcpServer
{
    Q_OBJECT
public:
    Server(QObject *parent = 0,int port=0);

    QList<TcpClientSocket*> tcpClientSocketList;
    //这个尖括号代表什么意思??
signals:
    void updateServer(QString,int);
public slots:
    void updateClients(QString,int);
    void slotDisconnected(int);
protected:
    void incomingConnection(int socketDescriptor);

};
#endif


#include "server.h"
Server::Server(QObject *parent,int port)
    :QTcpServer(parent)
{
    listen(QHostAddress::Any,port);
}
void Server::incomingConnection(int socketDescriptor)
{
    TcpClientSocket *tcpClientSocket = new TcpClientSocket(this);
    connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));
    //上面的那个为什么信号和槽是一样的??
    connect(tcpClientSocket,SIGNAL(disconnected(int))         ,this,SLOT(slotDisconnected(int)));

    tcpClientSocket->setSocketDescriptor(socketDescriptor);

    tcpClientSocketList.append(tcpClientSocket);
}
void Server::updateClients(QString msg, int length)
{
    emit updateServer(msg,length);//没有函数定义,那它怎么成为信号的??

    for(int i  = 0;i < tcpClientSocketList.count();i++)
    {
        QTcpSocket *item = tcpClientSocketList.at(i);
        if(item->write(msg.toLatin1(),length) != length)//这句有什么用,我觉得没啥用好像多余的
        {                                               //直接item->write(msg.toLatin1(),length)不就行了吗??
            continue;
        }
    }
}
void Server::slotDisconnected(int descriptor)
{
    for(int i  = 0;i < tcpClientSocketList.count();i++)
    {
        QTcpSocket *item = tcpClientSocketList.at(i);
        if(item->socketDescriptor() == descriptor)
        {
            tcpClientSocketList.removeAt(i);
            continue;
        }
    }
  相关解决方案