1.
连接服务器
m_tcpSocket->connectToHost("127.0.0.1", 9877);
connected =
m_tcpSocket->waitForConnected();
只有使用waitForConnected()后,QTcpSocket才真正尝试连接服务器,并返回是否连接的结果。
2.
写数据
m_tcpSocket->write(str.toStdString().c_str(),
strlen(str.toStdString().c_str()));
m_tcpSocket->waitForBytesWritten();
当使用waitForBytesWritten()后,QTcpSocket才真正发送数据。
m_tcpSocket->write(str1.toStdString().c_str(),
strlen(str1.toStdString().c_str()));
m_tcpSocket->write(str2.toStdString().c_str(),
strlen(str2.toStdString().c_str()));
的结果是发送了str1str2
3.
断开与服务器的连接
m_tcpSocket->disconnectFromHost()
m_tcpSocket->waitForDisconnected()
4.
善于使用QTcpSocket的SIGNAL:connected(), disconnected(),
error(QAbstractSocket::SocketError)
配合自定义私有开关变量bool
connected, QTimer
可以实现自动重连接等逻辑。
这久在写一个基于TCP的通信程序,Server端用WinCE实现,而Client端用Qt实现,之前已写了一个VC的Client端,能正确向Server发送数据。
将Client端改用Qt实现后connectToHost()后,server端已能正确accept(),但就是write()后server的read函数无法响应。调试了半天没有成功,火大呀!今天试着输出socket的状态后得到如下:
-
bool TcpClient::newConnect(const QString &iAddr, quint16 iPort)
-
{
-
mSocket = newQTcpSocket(this);
-
mSocket->connectToHost(iAddr,iPort);
-
qDebug("State:%dn",mSocket->state()); // State:
2; 2代表ConnectingState,正确的应该为3(ConnectedState)
-
-
connect(mSocket,SIGNAL(readyRead()),this,SLOT(read()));
-
connect(mSocket,SIGNAL(disconnected()),this,SLOT(disConnect()));return(true);
-
}
-
-
qint64 TcpClient::write(const QByteArray &iData)
-
{
-
qint64len = mSocket->write(iData);
-
qDebug("State:%dn",mSocket->state()); // State: 2;
2代表ConnectingState,正确的应该为3(ConnectedState)
-
-
msleep(200);
-
return(len);
-
}
复制代码
通过输出状态,已经找到问题的所在,哎!都是业务不熟害的呀!
socket的连接是异步的,所以必须等连接建立完成才能使用,所以分别加入waitForConnected()和waitForBytesWritten()后调试通过。
-
bool TcpClient::newConnect(const QString &iAddr, quint16 iPort)
-
{
-
mSocket = newQTcpSocket(this);
-
mSocket->connectToHost(iAddr, iPort);
-
qDebug("State:%dn",mSocket->state()); // State:
2; 2代表ConnectingState,正确的应该为3(ConnectedState)
-
-
constintTimeout=5*1000;
-
if(!mSocket->waitForConnected(Timeout))
-
{
-
return(false);
-
}
-
qDebug("State:%dn",mSocket>state()); // State:
3(ConnectedState)正确
-
-
connect(mSocket,SIGNAL(readyRead()),this,SLOT(read()));
-
connect(mSocket,SIGNAL(disconnected()),this,SLOT(disConnect()));return(true);
-
}
-
-
qint64 TcpClient::write(const QByteArray &iData)
-
{
-
qint64len = mSocket->write(iData);
-
mSocket->waitForBytesWritten(300);
-
qDebug("State:%dn",mSocket->state()); // State:
3(ConnectedState)正确
-
-
msleep(200);
-
return(len);
-
}
阅读(541) | 评论(0) | 转发(0) |