remote: check read/write results, detect disconnections

This commit is contained in:
Maxime Coste 2012-10-26 13:45:32 +02:00
parent 1c3f6c314f
commit 73aa11ac16
2 changed files with 27 additions and 5 deletions

View File

@ -17,11 +17,20 @@ enum class RemoteUIMsg
Draw Draw
}; };
struct socket_error{};
class Message class Message
{ {
public: public:
Message(int sock) : m_socket(sock) {} Message(int sock) : m_socket(sock) {}
~Message() { ::write(m_socket, m_stream.data(), m_stream.size()); } ~Message()
{
if (m_stream.size() == 0)
return;
int res = ::write(m_socket, m_stream.data(), m_stream.size());
if (res == 0)
throw peer_disconnected{};
}
void write(const char* val, size_t size) void write(const char* val, size_t size)
{ {
@ -77,12 +86,21 @@ void write(Message& msg, const DisplayBuffer& display_buffer)
write(msg, display_buffer.lines()); write(msg, display_buffer.lines());
} }
void read(int socket, char* buffer, size_t size)
{
int res = ::read(socket, buffer, size);
if (res == 0)
throw peer_disconnected{};
if (res == -1)
throw socket_error{};
assert(res == size);
}
template<typename T> template<typename T>
T read(int socket) T read(int socket)
{ {
char value[sizeof(T)]; char value[sizeof(T)];
auto res = ::read(socket, value, sizeof(T)); read(socket, value, sizeof(T));
assert(res == sizeof(T));
return *(T*)(value); return *(T*)(value);
}; };
@ -92,8 +110,7 @@ String read<String>(int socket)
ByteCount length = read<ByteCount>(socket); ByteCount length = read<ByteCount>(socket);
char buffer[2048]; char buffer[2048];
assert(length < 2048); assert(length < 2048);
auto res = ::read(socket, buffer, (int)length); read(socket, buffer, (int)length);
assert(res == (int)length);
return String(buffer, buffer+(int)length); return String(buffer, buffer+(int)length);
}; };

View File

@ -7,6 +7,11 @@
namespace Kakoune namespace Kakoune
{ {
struct peer_disconnected : public runtime_error
{
peer_disconnected() : runtime_error("peer disconnected") {}
};
class RemoteUI : public UserInterface class RemoteUI : public UserInterface
{ {
public: public: