handled reveiving data in several parts and rebuild it (data sent in parts using ctrl+D. e.g. : com^Dman^Dd)
This commit is contained in:
42
Server.cpp
42
Server.cpp
@@ -113,20 +113,37 @@ void Server::handleClientConnection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Server::handleClientData(int fd) {
|
void Server::handleClientData(int fd) {
|
||||||
char buffer[BUFFER_SIZE] = {0};
|
std::string command;
|
||||||
|
char buffer[BUFFER_SIZE];
|
||||||
// Receive the data
|
memset(buffer, 0, sizeof(buffer));
|
||||||
ssize_t bytes = recv(fd, buffer, BUFFER_SIZE - 1 , 0);
|
|
||||||
|
ssize_t bytesRead;
|
||||||
// Check if the client disconnected
|
while ((bytesRead = recv(fd, buffer, BUFFER_SIZE - 1, 0)) > 0) {
|
||||||
if (bytes <= 0) {
|
bool foundEof = false;
|
||||||
|
for (ssize_t i = 0; i < bytesRead; ++i) {
|
||||||
|
if (buffer[i] == '\n') {
|
||||||
|
foundEof = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!foundEof) {
|
||||||
|
buffer[bytesRead] = '\0';
|
||||||
|
command += buffer;
|
||||||
|
} else {
|
||||||
|
command.append(buffer, bytesRead - 1);
|
||||||
|
std::cout << "Received data from client " << fd << ": " << command << std::endl;
|
||||||
|
// process the command here
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytesRead == 0) {
|
||||||
std::cout << "Client <" << fd << "> Disconnected" << std::endl;
|
std::cout << "Client <" << fd << "> Disconnected" << std::endl;
|
||||||
clientCleanup(fd);
|
clientCleanup(fd);
|
||||||
} else {
|
} else if (bytesRead == -1) {
|
||||||
buffer[bytes] = '\0';
|
std::cerr << "Error reading data from client <" << fd << ">" << std::endl;
|
||||||
std::cout << "Client <" << fd << "> Data: " << buffer;
|
clientCleanup(fd);
|
||||||
|
|
||||||
// parse, check, and handle the received data here
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,6 +151,7 @@ void Server::clientCleanup(int fd) {
|
|||||||
for (std::vector<pollfd>::iterator it = _fds.begin(); it != _fds.end(); ++it) {
|
for (std::vector<pollfd>::iterator it = _fds.begin(); it != _fds.end(); ++it) {
|
||||||
if (it->fd == fd) {
|
if (it->fd == fd) {
|
||||||
_fds.erase(it);
|
_fds.erase(it);
|
||||||
|
close(fd);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -9,6 +9,7 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
#include <poll.h>
|
#include <poll.h>
|
||||||
#include "Client.hpp"
|
#include "Client.hpp"
|
||||||
|
#include <cstring>
|
||||||
#define BUFFER_SIZE 1024
|
#define BUFFER_SIZE 1024
|
||||||
|
|
||||||
class Server {
|
class Server {
|
||||||
|
Reference in New Issue
Block a user