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 客户端


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01