zoukankan      html  css  js  c++  java
  • qt fortuneserver 例子学习 ( 给客户端发送消息) GIS

      qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

    http://blog.csdn.net/friendbaby/article/details/6862741

    http://bbs.csdn.net/topics/390027543

    首先是初始化:

    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    接着就可以随机了:
    qrand()理论上返回0 到 RAND_MAX间的值。
    如果要返回0~n间的值,则为:qrand()%n;
    如果要返回a~b间的值,则为:a + qrand() % (b - a)

    这里介绍2种方法

    看看里面的server 类 

    class Server : public QDialog// 继承自 qdialog
    {
    Q_OBJECT

    public:
    Server(QWidget *parent = 0);// 构造函数

    private slots:
    void sessionOpened();
    void sendFortune();

    private:
    QLabel *statusLabel;
    QPushButton *quitButton;
    QTcpServer *tcpServer;
    QStringList fortunes;
    QNetworkSession *networkSession;
    };

    看看 server 里面实现的构造函数

    Server::Server(QWidget *parent): QDialog(parent), tcpServer(0), networkSession(0)  // 初始化指针

    {

    }

    整个例子的思路就是 

    1   tcpServer = new QTcpServer(this);

    1.1  tcpServer->listen()

    1.2   connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));   //在信号newConnection 里面出发接受到连接

     2  QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();// 下面的代码是活的 非localhost 的ip 地址比如我现在的ip地址10.21.140.75而不是localhoust

    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
    if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
    ipAddressesList.at(i).toIPv4Address()) {
    ipAddress = ipAddressesList.at(i).toString();
    break;
    }
    }

    3 tcpServer->serverPort()// 获得一个端口

    4 当客户端连接之后  触发newConnection() 信号 ,然后 在sendFortune() 里面给 客户端发送消息:

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); // 通过这句话获得之前和客户端建立的连接
    connect(clientConnection, SIGNAL(disconnected()),clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->disconnectFromHost();//  和本地断开

  • 相关阅读:
    POJ 1325、ZOJ 1364、HDU 1150 Machine Schedule
    约数的计算
    Opencv距离变换distanceTransform应用——细化字符轮廓&&查找物体质心
    霍夫圆变换
    【奇葩笔试】—— printf() 作为函数的参数及其返回值
    【奇葩笔试】—— printf() 作为函数的参数及其返回值
    字典(dictionary)的设计
    字典(dictionary)的设计
    极值点、驻点、鞍点、拐点
    极值点、驻点、鞍点、拐点
  • 原文地址:https://www.cnblogs.com/gisbeginner/p/2790498.html
Copyright © 2011-2022 走看看