Simplest QT TCP client(最简单的 QT TCP 客户端)
问题描述
我想连接到一个监听服务器并传输一些数据.我查看了可用的示例,但它们似乎具有对我来说似乎没有多大帮助的额外功能(即连接、fortune 等).这是我到目前为止的代码:
I would like to connect to a listening server and transmit some data. I looked at the examples available but they seem to have extra functions that do not seem very helpful to me (i.e. connect, fortune, etc.). This is the code I have so far:
QTcpSocket t;
t.connectToHost("127.0.0.1", 9000);
假设服务器正在监听且健壮,我需要实现什么来发送数据类型为 QByteArray
的数据变量?
Assuming the server is listening and robust, what do I need to implement to send a data variable with datatype QByteArray
?
推荐答案
用 QTcpSocket 非常简单.像你一样开始......
very simple with QTcpSocket. Begin as you did...
void MainWindow::connectTcp()
{
QByteArray data; // <-- fill with data
_pSocket = new QTcpSocket( this ); // <-- needs to be a member variable: QTcpSocket * _pSocket;
connect( _pSocket, SIGNAL(readyRead()), SLOT(readTcpData()) );
_pSocket->connectToHost("127.0.0.1", 9000);
if( _pSocket->waitForConnected() ) {
_pSocket->write( data );
}
}
void MainWindow::readTcpData()
{
QByteArray data = pSocket->readAll();
}
但请注意,从 TcpSocket 读取数据时,您可能会在不止一次传输中接收数据,即.当服务器向您发送字符串123456"时,您可能会收到123"和456".您有责任检查传输是否完成.不幸的是,这几乎总是导致你的类是有状态的:类必须记住它所期望的传输,它是否已经开始以及是否完成.到目前为止,我还没有想出一个优雅的方法来解决这个问题.
Be aware, though, that for reading from the TcpSocket you may receive the data in more than one transmission, ie. when the server send you the string "123456" you may receive "123" and "456". It is your responsibility to check whether the transmission is complete. Unfortunately, this almost always results in your class being stateful: the class has to remember what transmission it is expecting, whether it has started already and if it's complete. So far, I haven't figured out an elegant way around that.
这篇关于最简单的 QT TCP 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最简单的 QT TCP 客户端
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07