forked from 21pages/Transmit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpclient.cpp
61 lines (55 loc) · 1.77 KB
/
tcpclient.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include "tcpclient.h"
#include "widget.h"
#include <QCoreApplication>
#include <QTime>
TcpClient::TcpClient(QObject *parent) : BaseParent(parent)
{
socket = new QTcpSocket(this);
connect(socket,&QTcpSocket::readyRead,this,&TcpClient::handleReadyRead);
}
bool TcpClient::Open(Para *para)
{
socket->connectToHost(para->ip, para->client_port);
QTime time;
time.start();
while((time.elapsed() < 10000) && (socket->state()!=QAbstractSocket::ConnectedState)) {
QCoreApplication::processEvents();
}
return (socket->state()==QAbstractSocket::ConnectedState);
}
void TcpClient::Close()
{
socket->disconnectFromHost();
}
void TcpClient::handleReadyRead()
{
Widget* wid = (Widget*)parent();
QByteArray data = socket->readAll();
QString logString = "";
logString = "TCPC" + socket->peerAddress().toString() + ":" + QString::number(socket->peerPort());
logString += QString::asprintf(" read(%d):", data.size());
for(int i = 0; i < data.size(); i++)
{
logString += QString::asprintf("%02X ", (unsigned char)data.at(i));
}
logString += "\n";
wid->appendLog(logString);
emit sig_recv_data(data);
}
void TcpClient::slot_send_data(QByteArray hex)
{
Widget* wid = (Widget*)parent();
if(socket->state() == QAbstractSocket::ConnectedState) {
QString logString = "";
logString = "TCPC" + socket->peerAddress().toString() + ":" + QString::number(socket->peerPort());
logString += QString::asprintf(" write(%d):", hex.size());
for(int i = 0; i < hex.size(); i++)
{
logString += QString::asprintf("%02X ", (unsigned char)hex.at(i));
}
logString += "\n";
wid->appendLog(logString);
socket->write(hex);
socket->flush();
}
}