qt socket编程

  1. dialog.c
  2. #include <QtGui>   
  3. #include <QtNetwork>   
  4. #include <QFile>   
  5. #include <QDir>   
  6. #include <stdlib.h>   
  7. #include "dialog.h"   
  8.    
  9.    
  10. Dialog::Dialog(QWidget *parent)   
  11.     : QDialog(parent)   
  12. {   
  13.      tcpSocket = new QTcpSocket(this);   
  14.        
  15.      timer1=new QTimer(this);   
  16.      //timer2=new QTimer(this);   
  17.        
  18.      serverLabel = new QLabel(QString::fromLocal8Bit("服务器ip:"));   
  19.      ipInfoLabel = new QLabel(QString::fromLocal8Bit("服务器port:"));   
  20.      sqlipLabel = new QLabel(QString::fromLocal8Bit("数据库ip:"));   
  21.      databaseLabel = new QLabel(QString::fromLocal8Bit("数据库名:"));   
  22.      sqluserLabel = new QLabel(QString::fromLocal8Bit("用户名:"));   
  23.      sqlpassLabel = new QLabel(QString::fromLocal8Bit("数据库密码:"));   
  24.      startdateLabel = new QLabel(QString::fromLocal8Bit("开始日期:"));   
  25.      starttimeLabel = new QLabel(QString::fromLocal8Bit("开始时间:"));   
  26.    
  27.      ComboBox = new QComboBox;   
  28.         
  29.      ComboBox->addItem(tr("local"));   
  30.      ComboBox->addItem(tr("center"));   
  31.      ComboBox->addItem(tr("liantong"));   
  32.      ComboBox->addItem(tr("yidong"));   
  33.         
  34.      ipInfoLineEdit = new QLineEdit(tr("hj"));   
  35.      sqlipLineEdit = new QLineEdit(tr("hj"));   
  36.      databaseLineEdit = new QLineEdit(tr("hj"));   
  37.      sqluserLineEdit = new QLineEdit(tr("hj"));   
  38.      sqlpassLineEdit = new QLineEdit(tr("hj"));   
  39.      startdateLineEdit=new QLineEdit(QDate::currentDate().toString("yyyy.MM.dd"));   
  40.      starttimeLineEdit=new QLineEdit(QTime::currentTime().toString("h:m:s"));   
  41.    
  42.      sqlpassLineEdit->setEchoMode(QLineEdit::Password);   
  43.         
  44.     // hostLineEdit->setReadOnly(true);   
  45.     // portLineEdit->setReadOnly(true);   
  46.      startdateLineEdit->setReadOnly(true);   
  47.      starttimeLineEdit->setReadOnly(true);   
  48.      //display.setReadOnly(true);   
  49.    
  50.      beginButton = new QPushButton(tr("Begin"));   
  51.      beginButton->setDefault(true);   
  52.      beginButton->setEnabled(true);   
  53.    
  54.      quitButton = new QPushButton(tr("Quit"));   
  55.    
  56.      buttonBox = new QDialogButtonBox;   
  57.      buttonBox->addButton(beginButton, QDialogButtonBox::ActionRole);   
  58.      buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);   
  59.    
  60.      connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));   
  61.      connect(beginButton,SIGNAL(clicked()), this, SLOT(begin()));   
  62.      connect(timer1, SIGNAL(timeout()), this, SLOT(sendFortune())); //设置发送数据报的大小   
  63.      //connect(timer2, SIGNAL(timeout()), this, SLOT(copy()));   
  64.         
  65.      QGridLayout *mainLayout = new QGridLayout;   
  66.        
  67.      mainLayout->addWidget(serverLabel, 0, 0);   
  68.      mainLayout->addWidget(ComboBox, 0, 1);   
  69.      mainLayout->addWidget(ipInfoLabel, 0, 2);   
  70.      mainLayout->addWidget(ipInfoLineEdit, 0, 3);   
  71.      mainLayout->addWidget(sqlipLabel, 1, 0);   
  72.      mainLayout->addWidget(sqlipLineEdit, 1, 1);   
  73.      mainLayout->addWidget(databaseLabel,1,2);   
  74.      mainLayout->addWidget(databaseLineEdit,1,3);   
  75.      mainLayout->addWidget(sqluserLabel,2,0);   
  76.      mainLayout->addWidget(sqluserLineEdit,2,1);   
  77.      mainLayout->addWidget(sqlpassLabel,2,2);   
  78.      mainLayout->addWidget(sqlpassLineEdit,2,3);   
  79.      mainLayout->addWidget(startdateLabel,3,0);   
  80.      mainLayout->addWidget(startdateLineEdit,3,1);   
  81.      mainLayout->addWidget(starttimeLabel,3,2);   
  82.      mainLayout->addWidget(starttimeLineEdit,3,3);   
  83.      mainLayout->addWidget(&display,4,0,20,4);   
  84.      mainLayout->addWidget(buttonBox,24,0,1,4);    
  85.         
  86.      setLayout(mainLayout);   
  87.      setWindowTitle(tr("Client_sendDataToCenter"));   
  88.       
  89. }   
  90.    
  91.    
  92. void Dialog::begin()   
  93. {   
  94.            
  95.   //创建日志文件夹   
  96.   filepath = dir.currentPath();   
  97.    
  98.   if(!filepath.contains("log_center_send"))    
  99.    {       
  100.     dir.mkdir("log_center_send");   
  101.     filepath += "/log_center_send/";   
  102.     dir.setCurrent(filepath);   
  103.    }   
  104.     dir.cdUp();   
  105.        
  106.     //连接数据库,用户名和密码从界面上填入获得   
  107.   db = QSqlDatabase::addDatabase("QSQLITE"); // 使用sqlserver数据库驱动       
  108.   db.setDatabaseName("E:/sqlite/oracle.db"); // 之前建立的数据库名   
  109.     if(!db.open())   
  110.     {   
  111.         // 打开数据库失败,显示错误原因   
  112.    display.append("cannot open database.");   
  113.    display.append("Reason: " + db.lastError().databaseText());   
  114.     }   
  115.    
  116.     getip(); //获得ip   
  117.         
  118.         
  119.     tcpSocket->connectToHost(host,port);   
  120.     if(tcpSocket->waitForConnected(5000)==false)   
  121.      {     
  122.       display.append("Failed to connect the server!!");   
  123.       return;   
  124.      }   
  125.      
  126.       //和服务器交互信息   
  127.   QByteArray block("IamOracleR"); //请求数据包格式   
  128.     tcpSocket->write(block);   
  129.   if(tcpSocket->waitForBytesWritten()==false)   
  130.    {      
  131.         display.append("Failed to communicate with  the server!");   
  132.         return;   
  133.    }   
  134.      
  135.   timer1->start(100);   
  136.      
  137.   numflag=0;   
  138.     
  139.     
  140.     display.append("The client is working now!!");   
  141.         
  142.  }   
  143.    
  144. void Dialog::getip()   
  145.    {   
  146.     QSqlQuery queryip;   
  147.     QSqlError errorip;   
  148.     queryip.prepare("select * from ipInfo where servername=:name ");   
  149.     queryip.bindValue(":name",ComboBox->currentText());     
  150.     if(queryip.exec())   
  151.       {   
  152.        queryip.first();   
  153.        //对port和host赋值   
  154.        port=queryip.value(2).toInt();   
  155.        host=queryip.value(1).toString();   
  156.        ipInfoLineEdit->setText(host+" "+queryip.value(2).toString());   
  157.      }   
  158.      else   
  159.        {   
  160.          //如果查询失败,显示错误   
  161.         errorip= queryip.lastError();    
  162.         display.append("From sqlite database,the ipInfo table: " + errorip.databaseText());   
  163.        }   
  164.     }   
  165.    
  166. void Dialog::sendFortune()   
  167.     {   
  168.     timer1->stop();   
  169.        
  170.       if((++numflag)==1000)     //标志位符合条件则备份   
  171.       {   
  172.             display.append("here");   
  173.             copy();   
  174.             numflag=0;   
  175.         }   
  176.        
  177.     QByteArray data; //数据库中包含的输出字段    
  178.        
  179.     QSqlQuery query;   
  180.     QSqlError error;    
  181.     int numRows,temp;   
  182.     if(query.exec("select * from tempOracle where flag='f' "))   
  183.       {     
  184.          // 询问数据库驱动,是否驱动含有记录影响行数的特性   
  185.        if(db.driver()->hasFeature(QSqlDriver::QuerySize))   
  186.         {   
  187.           numRows = query.size(); // 如果支持结果影响的行数,那么直接记录下来   
  188.         }    
  189.         else   
  190.         {   
  191.           query.last();           //否则定位到结果最后   
  192.           numRows = query.at() + 1;   
  193.         }   
  194.        query.first();   
  195.        if(numRows==-1)   
  196.         {   
  197.             timer1->start(100);   
  198.             return;   
  199.         }   
  200.        else   
  201.         {    
  202.           do   
  203.             {   
  204.              //依次取出数据,并存于字符串数组中   
  205.              data=query.value(1).toByteArray()+query.value(0).toByteArray();     
  206.                
  207.              fortune[query.at()].clear();   
  208.              fortune[query.at()]=data; //设置类型,包类型(1字节)+socket号(2字节)+数据   
  209.                 
  210.              display.append(query.value(0).toString());   
  211.              //对于已充值成功的记录,改变发送标志位   
  212.              QSqlQuery queryupdate;   
  213.              queryupdate.prepare("update tempOracle set flag='t' where data=:da");   
  214.              queryupdate.bindValue(":da",query.value(0));   
  215.              if(!queryupdate.exec())   
  216.               {   
  217.                 QSqlError errorup = queryupdate.lastError();    
  218.                 display.append("Failed to change the sendflag!Reason:"+errorup.databaseText());   
  219.                 log("Failed to change the sendflag"+fortune[query.at()]);                
  220.               }   
  221.              temp=query.at();   
  222.              }   
  223.            while(query.next()&&temp<4);   
  224.         }        
  225.       }   
  226.      else   
  227.       {   
  228.         //如果查询失败,发出错误信号   
  229.         error= query.lastError();    
  230.         display.append("From sqlite database,the handled table: " + error.databaseText());   
  231.         timer1->start(100);   
  232.         return;   
  233.       }   
  234.         
  235.      QByteArray string;   
  236.      QString tempstring;   
  237.      int i,j,fortunelen[5];   
  238.      for(i=0;i<=4;i++)   
  239.        {   
  240.          fortunelen[i]=fortune[i].size();   
  241.          string+=fortune[i];   
  242.        }   
  243.         
  244.      for(i=0;i<5;i++)   
  245.         {   
  246.            tempstring=QString("%1").arg(fortunelen[i]);   
  247.            int b=tempstring.size();   
  248.            for(j=0;j<4-b;j++)   
  249.             {   
  250.              tempstring="0"+tempstring;   
  251.             }   
  252.               
  253.            string+=tempstring.toLocal8Bit();   
  254.            fortune[i].clear();   
  255.         }   
  256.      tcpSocket->write(string);   
  257.      display.append("send"+string);   
  258.         
  259.      if(tcpSocket->waitForBytesWritten()==false)   
  260.        {      
  261.          display.append("Failed to send the data to center");   
  262.          log("Failed to send the data to center"+string);   
  263.          return;   
  264.        }   
  265.         
  266.      string.clear();   
  267.         
  268.      timer1->start(100);   
  269.         
  270.     }   
  271.    
  272.     
  273. void Dialog::copy()   
  274.     {   
  275.       int nums=0;   
  276.       display.append("copy");   
  277.       QSqlQuery querycopy;   
  278.       QByteArray data1;   
  279.       if(querycopy.exec("select * from tempOracle where flag='t'"))   
  280.       {     
  281.          // 询问数据库驱动,是否驱动含有记录影响行数的特性   
  282.         if(db.driver()->hasFeature(QSqlDriver::QuerySize))   
  283.         {   
  284.           nums = querycopy.size(); // 如果支持结果影响的行数,那么直接记录下来   
  285.         }    
  286.         else   
  287.         {   
  288.           querycopy.last();           //否则定位到结果最后   
  289.           nums= querycopy.at() + 1;   
  290.         }   
  291.        querycopy.first();   
  292.        if(nums==-1)   
  293.         {   
  294.            display.append("No data in the handled table,and cann`t copy");   
  295.              return;   
  296.        }   
  297.        else   
  298.        {      
  299.          do   
  300.          {   
  301.         //依次取出数据,并存于字符串数组中   
  302.          data1=querycopy.value(0).toByteArray();     
  303.               
  304.          QSqlQuery queryinsert;   
  305.          queryinsert.prepare("insert into copyTempOracle(data) values (:da1)");   
  306.          queryinsert.bindValue(":da1",(QString)data1);   
  307.          if(!queryinsert.exec())   
  308.           {   
  309.             QSqlError errorinsert;   
  310.             errorinsert = queryinsert.lastError();    
  311.             display.append("Failed to copy the data.Reason:"+errorinsert.databaseText());   
  312.             log("Failed to copy"+data1);   
  313.           }   
  314.               
  315.          QSqlQuery querydelete;   
  316.          querydelete.prepare("delete from tempOracle where data=:dat and flag='t'");   
  317.          querydelete.bindValue(":dat",querycopy.value(0).toString());   
  318.          if(!querydelete.exec())   
  319.           {   
  320.             QSqlError errordelete;   
  321.             errordelete = querydelete.lastError();    
  322.             display.append("Failed to delete the data after copy.Reason:"+errordelete.databaseText());   
  323.             log("Failed to delete from the handled."+data1);   
  324.           }   
  325.          }   
  326.          while(querycopy.next());   
  327.        }   
  328.      }   
  329.       else   
  330.       {   
  331.           QSqlError errorcopy=querycopy.lastError();   
  332.           display.append("Failed to query the handled table.Reason:"+errorcopy.databaseText());   
  333.       }   
  334.     }   
  335.            
  336.  void Dialog::log(QByteArray fortune)   
  337.      {   
  338.        QFile file(QString::fromLocal8Bit("%1.txt").arg(QString::fromLocal8Bit(fortune)));   
  339.        file.open(QIODevice::WriteOnly);   
  340.        QTextStream log(&file);    
  341.        log <<QString::fromLocal8Bit(fortune);   
  342.      } 

dialog.h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <QTcpSocket> #include <QtSql> #include <QSqlDatabase> #include <QTextEdit> #include <QTime> #include <QFile> #include <QDir> #include <QTimer> class QDialogButtonBox; class QLabel; class QLineEdit; class QPushButton; class QTcpSocket; class QTextEdit; class QSqlDatabase; class QSqlQuery; class QTime; class QDate; class Dialog : public QDialog { Q_OBJECT public: Dialog(QWidget *parent = 0); void getip(); void log(QByteArray); void copy(); //备份 private: //图形界面 QLabel *serverLabel; QLabel *ipInfoLabel; QLabel *sqlipLabel; QLabel *databaseLabel; QLabel *sqluserLabel; QLabel *sqlpassLabel; QLabel *startdateLabel; QLabel *starttimeLabel; QComboBox *ComboBox; QLineEdit *ipInfoLineEdit; QLineEdit *sqlipLineEdit; QLineEdit *databaseLineEdit; QLineEdit *sqluserLineEdit; QLineEdit *sqlpassLineEdit; QLineEdit *startdateLineEdit; QLineEdit *starttimeLineEdit; QPushButton *beginButton; QPushButton *quitButton; QDialogButtonBox *buttonBox; QTextEdit display; //存储服务器信息 int port; QString host; QString filepath; QDir dir; QByteArray fortune[5]; QTimer *timer1; // QTimer *timer2; QTcpSocket *tcpSocket; QSqlDatabase db; long numflag; public slots: //从套接字读数据,并存于数据库中 void sendFortune(); //创建数据库连接,开始定时 void begin(); }; #endif

main.c
  1. #include <QApplication>   
  2. #include <QtCore>   
  3.    
  4. #include <stdlib.h>   
  5.    
  6. #include "dialog.h"   
  7.    
  8. int main(int argc, char *argv[])   
  9. {   
  10.     QApplication app(argc, argv);   
  11.     Dialog dialog;   
  12.     dialog.show();   
  13.     return dialog.exec();   
  14. }   
原文地址:https://www.cnblogs.com/tuotuteng/p/3883612.html