最简单的 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.
相关文章