-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatserver.cpp
111 lines (101 loc) · 2.79 KB
/
chatserver.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "chatserver.h"
//Konstruktoren
ChatServer::ChatServer(QObject *parent) :
QObject(parent)
{
ConnectionList = new QList<ChatConnection*>();
setPort(2342);
bActive = false;
}
ChatServer::ChatServer(qint16 port, QObject *parent) :
QObject(parent)
{
ConnectionList = new QList<ChatConnection*>();
setPort(port);
bActive = false;
}
//setter and getter
void ChatServer::setPort(qint16 port)
{
if(port < 1024)
port = 1024;
iPort = port;
}
bool ChatServer::isListening()
{
return bActive;
}
//public slots
void ChatServer::startServer()
{
if(!bActive)
{
Server = new QTcpServer(this);
if(Server->listen(QHostAddress::AnyIPv6, iPort))
{
connect(Server, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
bActive = true;
QString sMessage = tr("Server gestartet, höre auf Port %0.").arg(iPort);
emit newLog(sMessage);
}
}
}
void ChatServer::stopServer()
{
if(bActive)
{
for(int i = 0; i < ConnectionList->count(); i++)
{
Connection = ConnectionList->at(i);
Connection->CloseAndDelete();
}
ConnectionList->clear();
Server->close();
Server->deleteLater();
QString sMessage = tr("Server und alle Verbindungen gestoppt.");
emit newLog(sMessage);
bActive = false;
}
}
//private slots
void ChatServer::handleNewConnection()
{
QTcpSocket *Socket = Server->nextPendingConnection();
Connection = new ChatConnection(this);
ConnectionList->append(Connection);
connect(Connection, SIGNAL(newLog(QString)), this, SLOT(forwardLog(QString)));
connect(Connection, SIGNAL(newMessage(QString,QString)), this, SLOT(handleMessage(QString,QString)));
connect(Connection, SIGNAL(aboutToClose(ChatConnection*)), this, SLOT(closeConnection(ChatConnection*)));
Connection->setSocket(Socket);
}
void ChatServer::closeConnection(ChatConnection *conn)
{
Connection = conn;
ConnectionList->removeAll(Connection);
QString sMessage = tr("Verbindung zu %0 wurde vom Client abgebrochen.")
.arg(Connection->nick());
emit newLog(sMessage);
Connection->CloseAndDelete();
}
void ChatServer::forwardLog(QString sMessage)
{
emit newLog(sMessage);
}
void ChatServer::handleMessage(QString sNick, QString sText)
{
QString sMessage = tr("Neue Nachricht von %0: %1")
.arg(sNick)
.arg(sText);
emit newLog(sMessage);
for(int i = 0; i < ConnectionList->count(); i++)
{
Connection = ConnectionList->at(i);
if(sNick != Connection->nick())
{
sMessage = tr("%0> %1")
.arg(sNick)
.arg(sText);
Connection->sendMessage(sMessage);
}
}
}