-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserverclass.cpp
More file actions
51 lines (44 loc) · 1.2 KB
/
serverclass.cpp
File metadata and controls
51 lines (44 loc) · 1.2 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
#include <QTcpServer>
#include <QTcpSocket>
#include "serverclass.h"
ServerClass::ServerClass(QObject *parent)
: QObject(parent)
{
server = new QTcpServer(this);
socket = new QTcpSocket(this);
}
ServerClass::~ServerClass()
{
delete socket;
}
bool ServerClass::startServer(QString ipAddress, quint16 port)
{
// Start the server
QHostAddress ip(ipAddress);
if (!server->listen(ip, port)) {
return false;
}
// Connect the server to the connection slot
connect(server, SIGNAL(newConnection()), this, SLOT(connection()));
return true;
}
// This is the slot that is called when the server receives a connection
void ServerClass::connection()
{
socket = server->nextPendingConnection();
// Connect the socket to the receiveMessage slot
connect(socket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
}
// This is the slot that is called when the server receives a message
void ServerClass::receiveMessage()
{
QByteArray data = socket->readAll();
QString message = QString::fromUtf8(data);
emit messageReceived(message, 0);
}
// This is the method that is called when the server sends a message
void ServerClass::sendMessage(QString message)
{
QByteArray data = message.toUtf8();
socket->write(data);
}