-
Notifications
You must be signed in to change notification settings - Fork 4
/
Server.cpp
83 lines (66 loc) · 2.18 KB
/
Server.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "Server.hpp"
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
#include "RemoteClient.hpp"
Server::Server(QObject *parent) :
QObject(parent),
m_server(new QTcpServer(this))
{
}
void Server::startServer(quint16 port)
{
bool started = m_server->listen(QHostAddress::Any, port);
connect(m_server, SIGNAL(newConnection()),
this, SLOT(onClientConnected()));
if (started) {
emit serverStarted(m_server->serverPort());
qDebug() << Q_FUNC_INFO << "Server started on port :" << m_server->serverPort();
}
}
void Server::sendMessage(QString message)
{
for (RemoteClient *client : m_clients) {
client->sendMessage(message);
}
}
void Server::onClientMessageReceived(QString message)
{
RemoteClient *client = qobject_cast<RemoteClient*>(sender());
sendMessage(message);
emit messageReceived(client->nickName(), message);
}
void Server::onClientConnected()
{
QTcpSocket *clientSocket = m_server->nextPendingConnection();
RemoteClient *client = new RemoteClient(clientSocket, this);
m_clients << client;
client->setNickname(clientSocket->peerAddress().toString());
for (RemoteClient *client : m_clients) {
client->sendMessage("client connect" + clientSocket->peerAddress().toString());
}
connect(client,SIGNAL(messageReceived(QString)),
this,SLOT(onClientMessageReceived(QString)));
connect(client,SIGNAL(wantParticipants()),
this, SLOT(sendParticipants()));
connect(client, SIGNAL(tunneledMessageReceived(int,QByteArray)),
this, SLOT(onTunneledMessageReceived(int,QByteArray)));
}
void Server::sendParticipants()
{
RemoteClient *client = qobject_cast<RemoteClient*>(sender());
int id = 0;
QList<int> ids;
QStringList names;
for (RemoteClient *client : m_clients) {
ids.append(id);
names.append(client->nickName());
id ++;
}
client->sendParticipants(ids, names);
}
void Server::onTunneledMessageReceived(int idTo, const QByteArray &message)
{
RemoteClient *clientFrom = qobject_cast<RemoteClient*>(sender());
m_clients[idTo]->sendTunneledMessage(m_clients.indexOf(clientFrom), message);
}