Zappy Server
C++ game server: world, rules, scheduler, network
Loading...
Searching...
No Matches
Connection.cpp
Go to the documentation of this file.
1#include "Connection.hpp"
2
3#include <sys/socket.h>
4#include <unistd.h>
5
6Connection::Connection(int fd) : _fd(fd) {}
7
9{
10 if (_fd >= 0) close(_fd);
11}
12
13void Connection::appendRead(std::string_view data) { _readBuf.append(data); }
14
15std::optional<std::string> Connection::nextLine()
16{
17 size_t pos = _readBuf.find('\n');
18 if (pos == std::string::npos) return std::nullopt;
19
20 std::string line = _readBuf.substr(0, pos);
21 _readBuf.erase(0, pos + 1);
22 return line;
23}
24
25void Connection::queueWrite(const std::string& msg) { _writeBuf.append(msg); }
26
28{
29 if (_writeBuf.empty()) return;
30 ssize_t sent = send(_fd, _writeBuf.data(), _writeBuf.size(), MSG_NOSIGNAL);
31 if (sent > 0) _writeBuf.erase(0, static_cast<size_t>(sent));
32}
33
34int Connection::fd() const { return _fd; }
37int Connection::playerId() const { return _playerId; }
39bool Connection::hasPendingWrite() const { return !_writeBuf.empty(); }
ClientType
Definition ClientType.hpp:7
static std::string id(int n)
Definition Serializer.cpp:3
void flushWrite()
Try to send the buffered write data over the socket.
void setType(ClientType type)
void queueWrite(const std::string &msg)
Append msg to the write buffer (not sent until flushWrite()).
bool hasPendingWrite() const
True if there is still unsent data in the write buffer.
std::optional< std::string > nextLine()
Pop one complete ' '-terminated line, or nullopt if none buffered yet.
ClientType type() const
Client kind: PENDING until the handshake promotes it to AI or GUI.
void appendRead(std::string_view data)
Append freshly-read bytes to the read buffer.
std::string _writeBuf
Connection(int fd)
Definition Connection.cpp:6
ClientType _type
void setPlayerId(int id)
int fd() const
int playerId() const
Player this connection drives (-1 for GUI / not yet assigned).
std::string _readBuf