欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Qt网络编程——TCP服务器与客户端互发信息

发布时间:2025/3/21 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Qt网络编程——TCP服务器与客户端互发信息 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

前言

前一个博客,试了TCP的服务器与客户端的连接与断开,接下就是客户端与服务器互发信息。

客户端

1.往服务器发送信息

//发送消息 void Client::on_buttonSendMessage_clicked() {QString data = ui->textEditInput->toPlainText();if(data.length() != 0){tcpClient->write(data.toLatin1());ui->textEditInput->clear();ui->textEditStatus->append("发送文本消息成功!");data.clear();}else{ui->textEditStatus->append("不能发送空的消息!");}}

当客户端连接上服务器之后,在输入窗口下输入文字(英文),然后点发送按键,信息往服务器发送。
2.接收来自服务器的信息
2.1 在构造函数里添加一个槽函数做接收到信息的事件响应

connect(tcpClient, SIGNAL(readyRead()), this, SLOT(readServerMessage()));

2.1 实现这个槽函数,接收信息并显示出来

//接收服务器端的信息并显示 void Client::readServerMessage() {QByteArray buffer = tcpClient->readAll();if(!buffer.isEmpty()){ui->textEditAccept->append(buffer);} }

服务器

1.在服务器要加上有新客户端连接时的槽函数

//有新的连接时的槽函数connect(tcpServer,SIGNAL(newConnection()),this, SLOT(newConnectionSlot()));

槽函数实现

//有新客户端连接时 void Server::newConnectionSlot() {//返回套接字指针currentClient = tcpServer->nextPendingConnection();tcpClient.append(currentClient);ui->comboBoxIP->addItem(tr("%1:%2").arg(currentClient->peerAddress().toString().split("::ffff:")[1])\.arg(currentClient->peerPort()));//读取消息处理connect(currentClient, SIGNAL(readyRead()), this, SLOT(readMessageData())); }

2.接收来自客户端的信息并显示出来

//接收消息并显示到界面 void Server::readMessageData() {for(int i = 0; i < tcpClient.length(); i++){QByteArray buffer = tcpClient.at(i)->readAll();if(buffer.isEmpty()){ui->textEditStatus->append("接收的消息为空!");}else{ui->textEditAccept->append(buffer);ui->textEditStatus->append("接收消息成功!");}} }

3.往客户端发送信息,这里有两种可能,一是只要连接上的客户端都发,二是指定客户端来发送,就是绑死客户端的IP地址。

//往客户端发送信息 void Server::on_buttonSendMessage_clicked() {QString input_data = ui->textEditInput->toPlainText();if(input_data.isEmpty()){ui->textEditStatus->append("不能发送空的信息!");return;}//如果选择全部发送信息if(ui->comboBoxIP->currentIndex() == 0){for(int i = 0; i < tcpClient.length(); i++){tcpClient.at(i)->write(input_data.toLatin1());ui->textEditStatus->append("信息发送成功!");ui->textEditInput->clear();input_data.clear();}}//指定接收的客户端else{//得到选择的IP地址QString client_IP = ui->comboBoxIP->currentText().split(":").at(0);//得到端口int client_port = ui->comboBoxIP->currentText().split(":").at(1).toInt();//遍历连接到的客户端for(int i = 0; i < tcpClient.length(); i++){if(tcpClient[i]->peerAddress().toString().split("::ffff:")[1]==client_IP\&& tcpClient[i]->peerPort()==client_port){tcpClient.at(i)->write(input_data.toLatin1());ui->textEditStatus->append("发送信息到:"+client_IP+"成功!");//ui->textEditInput->clear();input_data.clear();return; //ip:port唯一,无需继续检索}}} }

测试

运行服务器与客户端,并点击监听与连接,开始互发信息
运行效果如下:

以上是就是一个服务器与客户端的初步框架,还缺少了互相传送图像,上传下载文件这两个功能,还有异常处理机制,心跳检测,多线程等需要完善。

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的Qt网络编程——TCP服务器与客户端互发信息的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。