64 lines
1.9 KiB
C++
64 lines
1.9 KiB
C++
#include "TCPServerSocket.h"
|
|
#include "EPoll.h"
|
|
#include "Session.h"
|
|
#include "Exception.h"
|
|
|
|
namespace core {
|
|
|
|
TCPServerSocket::TCPServerSocket(EPoll &ePoll, IPAddress address) : TCPSocket(ePoll) {
|
|
|
|
setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
|
|
int yes = 1;
|
|
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
|
|
if(bind(getDescriptor(), address.pointer, sizeof(address)) < 0)
|
|
throw Exception("Error on bind to socket");
|
|
if(listen(getDescriptor(), 10) < 0)
|
|
throw Exception("Error on listen to socket");
|
|
ePoll.registerSocket(this);
|
|
service = _getService();
|
|
}
|
|
|
|
TCPServerSocket::~TCPServerSocket() {
|
|
close(getDescriptor());
|
|
}
|
|
|
|
void TCPServerSocket::init() {}
|
|
|
|
void TCPServerSocket::onDataReceived(std::string data) {
|
|
Log(LOG_DEBUG_2) << "Connection request on socket " << getDescriptor() << ".";
|
|
Session *session = accept();
|
|
service->sessions.push_back(session);
|
|
}
|
|
|
|
Session * TCPServerSocket::accept() {
|
|
Session *session = getSocketAccept();
|
|
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.address, &session->ipAddress.addressLength));
|
|
ePoll.registerSocket(session);
|
|
Log(LOG_DEBUG_2) << "Session started on socket " << session->getDescriptor() << ".";
|
|
return session;
|
|
}
|
|
|
|
Session * TCPServerSocket::getSocketAccept() {
|
|
return new Session(ePoll, *service);
|
|
}
|
|
|
|
Service * TCPServerSocket::_getService() {
|
|
return getService();
|
|
}
|
|
|
|
Service * TCPServerSocket::getService() {
|
|
return new Service(*this);
|
|
}
|
|
|
|
int TCPServerSocket::processCommand(std::string command, Session *session) {
|
|
int sequence = 0;
|
|
for(auto *sessionx : service->sessions) {
|
|
session->out << "|" << ++sequence;
|
|
sessionx->output(session);
|
|
session->out << "|" << std::endl;
|
|
}
|
|
session->send();
|
|
}
|
|
|
|
}
|