-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cpp
55 lines (46 loc) · 1.31 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
#include "Server.h"
#include "Connection.h"
Server::Server(QObject *parent)
: QTcpServer(parent)
{
}
bool Server::start(quint16 port)
{
return listen(QHostAddress::Any, port);
}
void Server::incomingConnection(qintptr handle)
{
emit logServer("Connected new client");
auto socket = new Connection(handle, this);
_connections << socket;
for (auto socket : _connections) {
QTextStream stream(socket);
stream << "Connected new client: " << handle;
socket->flush();
}
connect(socket, &Connection::ReadyRead, this, &Server::readyReadSocket);
connect(socket, &Connection::StateChanged, this, &Server::changedStateSocket);
}
void Server::readyReadSocket(Connection *socket)
{
emit logServer("ReadyRead");
QTextStream out(socket);
auto text = out.readAll();
for (auto socket : _connections) {
QTextStream in(socket);
in << text;
socket->flush();
}
}
void Server::changedStateSocket(Connection *socket, int state)
{
if (state == QTcpSocket::UnconnectedState) {
emit logServer("Unconnected one client");
_connections.removeOne(socket);
for (auto socket : _connections) {
QTextStream in(socket);
in << "Server: Client disconnected...";
socket->flush();
}
}
}