-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclientwindow.cpp
More file actions
81 lines (67 loc) · 1.94 KB
/
clientwindow.cpp
File metadata and controls
81 lines (67 loc) · 1.94 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "clientwindow.h"
#include "ui_clientwindow.h"
#include <QtDebug>
#include <QHostAddress>
int ClientWindow::clientIndex = 0;
ClientWindow::ClientWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::ClientWindow())
{
ui->setupUi(this);
socket = new RapidClient(this);
setAttribute(Qt::WA_DeleteOnClose, true);
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(error(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(stateChanged(QAbstractSocket::SocketState)));
clientId = ++clientIndex;
setWindowTitle(tr("客户端 #%1").arg(clientId));
socket->installRapidFilter(15, [=] (const RapidClientEvent &e) {
QString text = QString::fromUtf8(e.datagram);
ui->output->appendPlainText(text);
});
}
ClientWindow::~ClientWindow()
{
}
void ClientWindow::error(QAbstractSocket::SocketError socketError)
{
if (QTcpSocket::RemoteHostClosedError != socketError) {
qDebug() << socketError;
}
close();
}
void ClientWindow::stateChanged(QAbstractSocket::SocketState socketState)
{
switch (socketState) {
case QAbstractSocket::ConnectedState: {
QByteArray datagram;
QDataStream ds(&datagram, QIODevice::WriteOnly);
ds << clientId;
socket->writeDatagram(8, datagram);
break;
}
case QAbstractSocket::UnconnectedState:
this->close();
break;
default:
break;
}
}
void ClientWindow::on_writeButton_clicked()
{
QString text = ui->datagram->text();
if (!text.isEmpty() && QAbstractSocket::ConnectedState == socket->state()) {
socket->writeDatagram(15, text.toUtf8());
ui->datagram->clear();
}
}
void ClientWindow::on_closeButton_clicked()
{
socket->close();
close();
}
void ClientWindow::connectToHost(quint16 port)
{
socket->connectToHost(QHostAddress::LocalHost, port);
}