将上次的登录改为TCP/IP通信。通信主要用到了两个类QTcpServer和QTcpsocket。QTcpServer对象负责监听是否有客户端连接此服务器,它是通过listen函数监听的。服务端和客户端通过套接字QTcpSocket进行通信。
服务端代码:
Server::Server(QObject *parent): QObject(parent)
{
server = new QTcpServer();
//它的第一个参数表示服务器监听的地址,后面的Any表示监听本机的所有网口的,第二个参数表示监听的网络端口
server->listen(QHostAddress::Any, 8342);
//如果服务器监听到有客户端和它进行连接,服务器就会触发newConnection这个信号
QObject::connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
}
void Server::acceptConnection()
{ //通过nextPendingConnection函数返回建立好连接的套接字
clientConnection = server->nextPendingConnection();
//服务器端有客户端数据写入时服务器端会自动调用readyread信号
QObject::connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readInfo()));
}
void Server::readInfo(){
//接收信息
QByteArray dataread = clientConnection->readAll();
QString userName = QString::fromLocal8Bit(dataread);
//查询密码(查询过程省略)
QString result = " "
//......
//......
//result = 查询到的结果
//发送结果
clientConnection->write(result.toLocal8Bit());
}
客户端代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//初始化界面
ui->setupUi(this);
userAct = new QAction(this);
userAct->setIcon(QIcon(":/login/userNameLineedit.png"));
passwordAct = new QAction(this);
passwordAct->setIcon(QIcon(":/login/passwordLineedit.png"));
init();
//初始化套接字
connection = new QTcpSocket(this);
connection->connectToHost(QHostAddress("127.0.0.1"), 8342);
connect(connection, SIGNAL(readyRead()), this, SLOT(readInfo()));
}
//点击登录按钮的槽函数
void MainWindow::on_loginButton_clicked()
{
if(ui->userNameLine->text()=="") return;
if(ui->passwordLine->text() =="") return;
qDebug()<<ui->passwordLine->text();
//向服务端发送数据
connection->write(ui->userNameLine->text().toLocal8Bit());
}
//接收服务端数据
void MainWindow::readInfo(){
QByteArray byteArray = connection->readAll();
QString password = QString::fromLocal8Bit(byteArray);
qDebug()<<password;
if(password == ui->passwordLine->text()) {
QMessageBox::information(this, "登录成功", "登录成功",QMessageBox::Ok,QMessageBox::NoButton);
}
else{
QMessageBox::information(this, "登录失败", "登录失败",QMessageBox::Ok,QMessageBox::NoButton);
}
}
服务端与客户端通信的基本步骤:
1. QTcpServer对象监听是否有客户端连接此服务器
2. 如果服务器监听到有客户端和它进行连接,服务器就会触发newConnection这个信号
3. 通过nextPendingConnection函数返回建立好连接的套接字
4. 当一端发送信息之后,接收方会触发信号readyRead
5. 读取信息并处理
客户端和服务端采用了QString::fromLocal8Bit(QByteArray *byteArray)和QString.toLocal8Bit()来进行解码和编码。另外,信号与槽关联函数connect是QObject中的函数,要使用的话必须继承QObject类。
{{ cmt.username }}
{{ cmt.content }}
{{ cmt.commentDate | formatDate('YYYY.MM.DD hh:mm') }}