forked from junbinxu/chess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchessserver.cpp
More file actions
71 lines (61 loc) · 1.53 KB
/
chessserver.cpp
File metadata and controls
71 lines (61 loc) · 1.53 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
#include "chessserver.h"
#include "chesslog.h"
#include "chessinformation.h"
#include <QTcpServer>
#include <QTcpSocket>
ChessServer * ChessServer::INSTANCE = 0;
ChessServer * ChessServer::instance()
{
if(!INSTANCE)
{
INSTANCE = new ChessServer;
}
return INSTANCE;
}
ChessServer::ChessServer(QObject *parent) :
ChessOpposition(parent), socket(0)
{
server = new QTcpServer(this);
quint16 port = ChessInformation::instance()->getServerPort();
bool ok = server->listen(QHostAddress::Any, port);
if(ok)
{
connect(server, SIGNAL(newConnection()), this, SLOT(newConnect()));
Chess_Info(tr("start server at port=%1 ok").arg(port));
}
else
{
Chess_Error(tr("server listen error"));
}
Chess_Trace(tr("new ChessServer"));
}
ChessServer::~ChessServer()
{
Chess_Trace(tr("delete ChessServer"));
}
bool ChessServer::isValid()
{
if(socket)
{
if(socket->state() != QAbstractSocket::ConnectedState) return false;
if(socket->isValid()) return true;
}
return false;
}
void ChessServer::newConnect()
{
socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), this, SLOT(read()));
}
void ChessServer::read()
{
QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
receive(QString(socket->readAll()));
}
void ChessServer::send(const QString &message)
{
if(isValid())
{
socket->write(message.toLocal8Bit());
}
}