用QT编写基于TCP的网络通信程序
我编写的是一个类似实时做题的小程序,不多bb,看演示如下:
算了,还是描述下上图的操作过程(真香~~)
- 运行服务器端先监听本地ip为
127.0.0.1
,端口是8081
(无所谓的) - 运行客户端,让它连接上服务器
- 服务器端发送题目到客户端
- 客户端就可以开始做题,做完题后,点击提交
- 服务器端就是收到信息,了解到客户端做题结果
其余说明:
- 服务器端的题目是写死在程序中
- 服务器端的日志框显示的是所有的日志情况,包括客户端和服务器端
- 代码:https://github.com/duganlx/CDforQT
操作小记
Qt使用网络通信环境配置
//.pro文件中引入
QT += network
//引入相关头文件
//client
#include <QTcpSocket>
#include <QHostAddress>
//server
#include <QTcpServer>
#include <QTcpSocket>
#include <QNetworkInterface>
客户端编写
连接服务器
void Widget::on_connectServer_clicked()
{
QString ipAddr = ui->ipAddr->text();
quint16 port = ui->port->text().toUShort();
client->connectToHost(ipAddr, port);
qDebug()<<"connecting server...";
if(client->waitForConnected(1000))
{
qDebug()<<"connect server success";
QMessageBox::information(NULL, "提示", "连接成功", QMessageBox::Ok);
ui->disconnectServer->setEnabled(true);
ui->connectServer->setEnabled(false);
}
else
{
QMessageBox::critical(NULL, "提示", "连接失败,请检查ip地址和端口号", QMessageBox::Ok);
}
}
断开服务器
void Widget::on_disconnectServer_clicked()
{
client->disconnectFromHost();
qDebug()<<"disconnecting server...";
if(client->state() == QAbstractSocket::UnconnectedState
|| client->waitForDisconnected(1000))
{
qDebug()<<"disconnect server success";
QMessageBox::information(NULL, "提示", "断开成功", QMessageBox::Ok);
ui->disconnectServer->setEnabled(false);
ui->connectServer->setEnabled(true);
}
else
{
QMessageBox::critical(NULL, "提示", "断开失败,请重试", QMessageBox::Ok);
}
}
接收数据
void Widget::receiveData()
{
qDebug()<<"receiveData()";
QByteArray buffer = client->readAll();
if(!buffer.isEmpty())
{
data = QTextCodec::codecForName("UTF-8")->toUnicode(buffer);
qDebug()<<data;
}
QStringList datas = data.split(",");
//填充数据到对应控件
ui->content->setText(datas.at(0));
ui->buttonA->setText("选项A "+ datas.at(2));
ui->buttonB->setText("选项B "+ datas.at(3));
ui->buttonC->setText("选项C "+ datas.at(4));
ui->buttonD->setText("选项D "+ datas.at(5));
}
发送数据
void Widget::on_commit_clicked()
{
//对应关系:A-0 B-1 C-2 D-3
QString clientChoice;
switch (optionGroup->checkedId())
{
case 0:
clientChoice = "A";
break;
case 1:
clientChoice = "B";
break;
case 2:
clientChoice = "C";
break;
case 3:
clientChoice = "D";
break;
}
if(clientChoice == data.split(",")[1])
{
clientChoice.append(",答案正确");
QMessageBox::information(NULL, "提示", "回答正确(●'◡'●)", QMessageBox::Ok);
}
else
{
clientChoice.append(",答案错误");
QMessageBox::information(NULL, "提示", "回答错误( ▼-▼ )", QMessageBox::Ok);
}
qDebug()<<"commit data to server: "<<clientChoice.toUtf8();
client->write(clientChoice.toUtf8());
}
服务器编写
获取所有连接的客户端
void Widget::connectingClient()
{
client = server->nextPendingConnection(); //获取连接过来的客户端信息
clients.append(client); //添加入客户端列表
ui->journal->append("客户端("+client->peerAddress().toString().split("::ffff:")[1]+":"+QString::number(client->peerPort())+") 连接服务器");
//绑定槽函数
connect(client, SIGNAL(readyRead()), this, SLOT(receiveData()));
connect(client, SIGNAL(disconnected()), this, SLOT(disconnectedClient()));
}
断开所有的客户端
void Widget::disconnectedClient()
{
//由于disconnected信号并未提供SocketDescriptor,所以需要遍历寻找
for(int i=0; i<clients.length(); i++)
{
if(clients[i]->state() == QAbstractSocket::UnconnectedState)
{
//删除记录
ui->journal->append("客户端("+clients[i]->peerAddress().toString().split("::ffff:")[1]+":"+QString::number(clients[i]->peerPort())+") 断开连接");
clients[i]->destroyed();
clients.removeAt(i);
}
}
}
接收数据
void Widget::receiveData()
{
qDebug()<<"receiveData()";
for(int i=0; i<clients.length(); i++)
{
QByteArray buffer = clients[i]->readAll();
if(buffer.isEmpty()) continue;
QString data = QTextCodec::codecForName("UTF-8")->toUnicode(buffer);
QStringList datas = data.split(",");
QString message = tr("客户端(%1:%2):所选答案为:%3,%4").arg(clients[i]->peerAddress().toString().split("::ffff:")[1])
.arg(clients[i]->peerPort()).arg(datas.at(0)).arg(datas.at(1));
ui->journal->append(message);
}
}
发送数据
void Widget::on_sendData_clicked()
{
qDebug()<<"sendData(),selected:"<<ui->questionList->currentRow();
int questionId = ui->questionList->currentRow();
if(questionId>=0&&questionId<=3)
{
targetQuestion = questionList[questionId];
QMessageBox::information(NULL, "提示", "发送题目成功", QMessageBox::Ok);
}
else
{
QMessageBox::information(NULL, "提示", "请选择题目", QMessageBox::Ok);
}
qDebug()<<"question data: "+targetQuestion->getStr();
for(int i=0; i<clients.length(); i++)
{
ui->journal->append("客户端("+clients[i]->peerAddress().toString()+":"+QString::number(clients[i]->peerPort())+")发送习题"+
QString::number(questionId));
clients[i]->write(targetQuestion->getStr().toUtf8());
}
}