22 m_pTcpSocket =
new QTcpSocket(
this);
24 m_pTcpSocket->connectToHost(strHost, nPort);
25 connect(m_pTcpSocket, SIGNAL(connected()), SLOT(slotConnected()));
26 connect(m_pTcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead()));
27 connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
28 this, SLOT(slotError(QAbstractSocket::SocketError))
31 m_ptxtInfo =
new QTextEdit;
32 m_ptxtInput =
new QLineEdit;
34 connect(m_ptxtInput, SIGNAL(returnPressed()),
35 this, SLOT(slotSendToServer())
37 m_ptxtInfo->setReadOnly(
true);
39 QPushButton* pcmd =
new QPushButton(
"&Send");
40 connect(pcmd, SIGNAL(clicked()), SLOT(slotSendToServer()));
43 QVBoxLayout* pvbxLayout =
new QVBoxLayout;
44 pvbxLayout->addWidget(
new QLabel(
"<H1>Client</H1>"));
45 pvbxLayout->addWidget(m_ptxtInfo);
46 pvbxLayout->addWidget(m_ptxtInput);
47 pvbxLayout->addWidget(pcmd);
48 setLayout(pvbxLayout);
52 void MyClient::slotReadyRead()
54 QDataStream in(m_pTcpSocket);
55 in.setVersion(QDataStream::Qt_5_3);
57 if (!m_nNextBlockSize) {
58 if (m_pTcpSocket->bytesAvailable() < (int)
sizeof(quint16)) {
61 in >> m_nNextBlockSize;
64 if (m_pTcpSocket->bytesAvailable() < m_nNextBlockSize) {
71 m_ptxtInfo->append(time.toString() +
" " + str);
77 void MyClient::slotError(QAbstractSocket::SocketError err)
80 "Error: " + (err == QAbstractSocket::HostNotFoundError ?
81 "The host was not found." :
82 err == QAbstractSocket::RemoteHostClosedError ?
83 "The remote host is closed." :
84 err == QAbstractSocket::ConnectionRefusedError ?
85 "The connection was refused." :
86 QString(m_pTcpSocket->errorString())
88 m_ptxtInfo->append(strError);
92 void MyClient::slotSendToServer()
95 QDataStream out(&arrBlock, QIODevice::WriteOnly);
96 out.setVersion(QDataStream::Qt_5_3);
97 out << quint16(0) << QTime::currentTime() << m_ptxtInput->text();
99 out.device()->seek(0);
100 out << quint16(arrBlock.size() -
sizeof(quint16));
102 m_pTcpSocket->write(arrBlock);
103 m_ptxtInput->setText(
"");
107 void MyClient::slotConnected()
109 m_ptxtInfo->append(
"Received the connected() signal");
MyClient(const QString &strHost, int nPort, QWidget *pwgt=0)