问题描述
我是新的QT ..我想连接到侦听服务器和传输一些数据。我看了看可用的例子,但他们似乎有额外的功能,对我看起来不是很有帮助(连接,财富等。)
I am new to QT.. 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 (connect, fortune, etc..)
QTcpSocket t;
t.connectToHost("127.0.0.1", 9000);
假设服务器正在监听和稳健。我需要发送QByteArray的data变量。
Assuming the server is listening and robust.. What do I need to send QByteArray of "data" variable.
使用QTcpSocket非常简单。
Much appreciated.
推荐答案
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客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!