服务器代码:
#include "dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
tcpServer=new QTcpServer(this);
tcpServer->listen(QHostAddress::Any,6677);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newClient()));
QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("my.db");
db.open();
}
Dialog::~Dialog()
{
}
void Dialog::newClient()
{
nextBlockSize=0;
QTcpSocket *tcpSocket=tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readClient()));
connect(tcpSocket,SIGNAL(disconnected()),tcpSocket,SLOT(deleteLater()));
}
void Dialog::readClient()
{
QTcpSocket *tcpSocket=qobject_cast<QTcpSocket*>(sender());
QDataStream in(tcpSocket);
if(nextBlockSize==0) {
if(tcpSocket->bytesAvailable() < sizeof(quint16))
return;
in >> nextBlockSize;
}
if(tcpSocket->bytesAvailable() < nextBlockSize)
return;
quint8 type;
QString username,password,word;
in >> type;
if(type!='Q') {
in >> username >> password;
processLogin(tcpSocket,type,username,password);
}else {
in >> word;
processFind(tcpSocket,word);
}
tcpSocket->close();
}
void Dialog::processLogin(QTcpSocket *tcpSocket, quint8 type, QString &username, QString password)
{
QByteArray buf;
QDataStream out(&buf,QIODevice::WriteOnly);
out << quint16(0) << quint8(type);
QSqlQuery query("select * from users");