⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dialog.cpp

📁 QT网络编程中收数据的客户端
💻 CPP
字号:
#include <QtGui>
#include <QtNetwork>
#include <QFile>
#include <QDir>
#include <stdlib.h>
#include "dialog.h"


Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
     tcpSocket = new QTcpSocket(this);
     
     serverLabel = new QLabel(QString::fromLocal8Bit("服务器ip:"));
     ipInfoLabel = new QLabel(QString::fromLocal8Bit("服务器port:"));
     sqlipLabel = new QLabel(QString::fromLocal8Bit("数据库ip:"));
     databaseLabel = new QLabel(QString::fromLocal8Bit("数据库名:"));
     sqluserLabel = new QLabel(QString::fromLocal8Bit("用户名:"));
     sqlpassLabel = new QLabel(QString::fromLocal8Bit("数据库密码:"));
     startdateLabel = new QLabel(QString::fromLocal8Bit("开始日期:"));
     starttimeLabel = new QLabel(QString::fromLocal8Bit("开始时间:"));

     ComboBox = new QComboBox;
     
     ComboBox->addItem(tr("local"));
     ComboBox->addItem(tr("center"));
     ComboBox->addItem(tr("liantong"));
     ComboBox->addItem(tr("yidong"));
     
     ipInfoLineEdit = new QLineEdit(tr("hj"));
     sqlipLineEdit = new QLineEdit(tr("hj"));
     databaseLineEdit = new QLineEdit(tr("hj"));
     sqluserLineEdit = new QLineEdit(tr("hj"));
     sqlpassLineEdit = new QLineEdit(tr("hj"));
     startdateLineEdit=new QLineEdit(QDate::currentDate().toString("yyyy.MM.dd"));
     starttimeLineEdit=new QLineEdit(QTime::currentTime().toString("h:m:s"));

     sqlpassLineEdit->setEchoMode(QLineEdit::Password);
     
   //  hostLineEdit->setReadOnly(true);
     ipInfoLineEdit->setReadOnly(true);
     startdateLineEdit->setReadOnly(true);
     starttimeLineEdit->setReadOnly(true);
     //display.setReadOnly(true);

     beginButton = new QPushButton(tr("Begin"));
     beginButton->setDefault(true);
     beginButton->setEnabled(true);

     quitButton = new QPushButton(tr("Quit"));

     buttonBox = new QDialogButtonBox;
     buttonBox->addButton(beginButton, QDialogButtonBox::ActionRole);
     buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

     connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
     connect(beginButton,SIGNAL(clicked()), this, SLOT(begin()));
     connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readFortune())); 
    
     QGridLayout *mainLayout = new QGridLayout;
    
     mainLayout->addWidget(serverLabel, 0, 0);
     mainLayout->addWidget(ComboBox, 0, 1);
     mainLayout->addWidget(ipInfoLabel, 0, 2);
     mainLayout->addWidget(ipInfoLineEdit, 0, 3);
     mainLayout->addWidget(sqlipLabel, 1, 0);
     mainLayout->addWidget(sqlipLineEdit, 1, 1);
     mainLayout->addWidget(databaseLabel,1,2);
     mainLayout->addWidget(databaseLineEdit,1,3);
     mainLayout->addWidget(sqluserLabel,2,0);
     mainLayout->addWidget(sqluserLineEdit,2,1);
     mainLayout->addWidget(sqlpassLabel,2,2);
     mainLayout->addWidget(sqlpassLineEdit,2,3);
     mainLayout->addWidget(startdateLabel,3,0);
     mainLayout->addWidget(startdateLineEdit,3,1);
     mainLayout->addWidget(starttimeLabel,3,2);
     mainLayout->addWidget(starttimeLineEdit,3,3);
     mainLayout->addWidget(&display,4,0,20,4);
     mainLayout->addWidget(buttonBox,24,0,1,4); 
     
     setLayout(mainLayout);
     setWindowTitle(tr("Fortune Client-getdata"));
   
}


void Dialog::begin()
{
  //创建日志文件夹
  QString filepath;
  QDir dir;
  filepath = dir.currentPath();

  if(!filepath.contains("log_center_receive"))	
   {	
    dir.mkdir("log_center_receive");
    filepath += "/log_center_receive/";
    dir.setCurrent(filepath);
   }
	
	//连接数据库,用户名和密码从界面上填入获得
  db = QSqlDatabase::addDatabase("QSQLITE"); // 使用sqlserver数据库驱动    
  db.setDatabaseName("E:/sqlite/oracle.db"); // 之前建立的数据库名
  //db.setUserName(username);       // 之前创建的用户名
  //db.setPassword(password);     //用户的密码
	if(!db.open())
	 {
	   display.append("cannot open database.");    // 打开数据库失败,显示错误原因
     display.append("Reason: " + db.lastError().databaseText());
	 }
	
	
	getip();     //获得ip
	
	
	tcpSocket->connectToHost(host,port);
	if(tcpSocket->waitForConnected(3000)==false)
    {  
      display.append("Failed to connect to the server!");
      return;
    }
	  
	  
	  //和服务器交互信息
  QByteArray block("IamOracleW"); //请求数据包格式
	tcpSocket->write(block);
  if(tcpSocket->waitForBytesWritten()==false)
   {   
        display.append("Failed to send the information to the server!");
        return;
   }
   
	 display.append("The client is working now!");
	}

void Dialog::getip()
   {
    QSqlQuery queryip;
    QSqlError errorip;
    queryip.prepare("select * from ipInfo where servername=:name ");
    queryip.bindValue(":name",ComboBox->currentText());  
    if(queryip.exec())
      {
       queryip.first();
       //对port和host赋值
       port=queryip.value(2).toInt();
       host=queryip.value(1).toString();
       ipInfoLineEdit->setText(host+" "+queryip.value(2).toString());
     }
     else
       {
         //如果查询失败,显示错误
        errorip= queryip.lastError(); 
        display.append("From sqlite database,the ipInfo table: " + errorip.databaseText());
       }
    
    
   }

void Dialog::readFortune()
	{
	
	QByteArray tempArray[5];
    
    QByteArray temp=tcpSocket->readAll(); 
	if(temp.size()==0)
	{
		display.append("error"); 
	}
    QByteArray type=temp.mid(9,6);
    display.append(temp);
    if(type=="211001")
     {
       writeData(temp.left(100));       //长度未知????
     }
    else
    {
      int i,leng[5],j=0;
      for(i=0;i<5;i++)
       {
        leng[i]=temp.mid((temp.size()-20+i*4),4).toInt();    //格式:socket号+数据  
        tempArray[i]=temp.mid(j,leng[i]);
        j=j+leng[i];
     	  if(leng[i]!=0)
     	  	{
     	      writeData(tempArray[i]);
     	    }
       }
    } 
    display.append("write");  
	  tcpSocket->write("OracleWReady"); //返回确认信息
    if(tcpSocket->waitForBytesWritten()==false)
     {   
        display.append("Failed to send the ACK to the server!");
        return;
     }
     
	}

 void Dialog::writeData(QByteArray temparray)
  { 
    QByteArray socketnum;     
    QByteArray data;
    display.append(temparray);
   	socketnum=temparray.left(5); 
    data=temparray.right(temparray.size()-5);     //未取年份
 
    QSqlQuery query;
    QSqlError error;
    query.prepare("insert into oracle(packet,socketnum) values (:pa,:socket)");
    query.bindValue(":pa",(QString)data);
    query.bindValue(":socket",(QString)socketnum);
    if(!query.exec())
      {
        //如果查询失败,返回错误信息
        error = query.lastError(); 
        QString temp="From oracle database,the oracle table: "+ error.databaseText(); 
        display.append(temp);
        
        QString fortune="Not insert sucesfully"+QString::fromLocal8Bit(data+socketnum)+QTime::currentTime().toString("HH:mm:ss");
        QFile file(fortune);
        file.open(QIODevice::WriteOnly);
        QTextStream log(&file); 
        log <<(data+socketnum)<<"\n";
      }
        
   }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -