16,235
社区成员
发帖
与我相关
我的任务
分享
#include "myclient2.h"
MyClient2::MyClient2(QWidget *parent, Qt::WFlags flags)
: QDialog(parent, flags)
{
ui.setupUi(this);
m_TcpSocket = new QTcpSocket(this);
connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(CF_Connect()));
//connect(m_TcpSocket,SIGNAL(hostFound()),this,SLOT(CF_HostFound()));
connect(m_TcpSocket,SIGNAL(readyRead()),this,SLOT(CF_ReadyRead()));
connect(m_TcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(displayError(QAbstractSocket::SocketError)));
}
MyClient2::~MyClient2()
{
}
void MyClient2::CF_Connect()
{
m_iBlockSize =0;
m_TcpSocket->abort();
//connect(m_TcpSocket,SIGNAL(disconnected()),m_TcpSocket,SLOT(deleteLater()));
m_TcpSocket->connectToHost(ui.Caddress->text(),ui.Cport->text().toInt());
}
void MyClient2::CF_ReadyRead()
{
QMessageBox::information(NULL,tr("Yes Connect"),tr("YES"));
QDataStream in(m_TcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if(m_iBlockSize == 0)
{
if(m_TcpSocket->bytesAvailable() < (int)sizeof(quint16))
{
return ;
}
}
in>>m_iBlockSize;
if(m_TcpSocket->bytesAvailable() < m_iBlockSize)
{
return ;
}
QString s_NextFortune;
in>>s_NextFortune;
if(s_NextFortune == m_sReadyRead)
{
QTimer::singleShot(0,this,SLOT(CF_Connect()));
return ;
}
m_sReadyRead = s_NextFortune;
ui.textEdit->setText(m_sReadyRead);
return ;
}
void MyClient2::CF_HostFound()
{
//QMessageBox::information(this,tr("Yes ChostFound"),tr("hostFound"));
}
void MyClient2::displayError(QAbstractSocket::SocketError socketError)
{
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
QMessageBox::information(this, tr("Fortune Client"),
tr("The host was not found. Please check the "
"host name and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
QMessageBox::information(this, tr("Fortune Client"),
tr("The connection was refused by the peer. "
"Make sure the fortune server is running, "
"and check that the host name and port "
"settings are correct."));
break;
default:
QMessageBox::information(this, tr("Fortune Client"),
tr("The following error occurred: %1.")
.arg(m_TcpSocket->errorString()));
}
}
注我几个函数都声明为了slot