20
GIOSocket() : con(0), read_tag(0), write_tag(0), outp(0) {}
21
virtual ~GIOSocket() { close(); }
23
bool isok() { return con; }
27
fcntl(fd, F_SETFD, O_NONBLOCK);
29
con = g_io_channel_unix_new(fd);
30
read_tag = g_io_add_watch(con,
31
(GIOCondition)(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),
35
void write(const string &line)
38
write_tag = g_io_add_watch(con, G_IO_OUT, _write_event, this);
40
outbuf.push_back(line);
47
g_io_channel_close(con);
48
g_io_channel_unref(con);
51
g_source_remove(write_tag);
53
g_source_remove(read_tag);
54
write_tag = read_tag = 0;
61
virtual void process_line(const string &line) = 0;
62
virtual void connection_lost() = 0;
64
static gboolean _read_event(GIOChannel *source,
65
GIOCondition condition, gpointer data)
67
GIOSocket *s = (GIOSocket*)data;
68
return s->read_event(condition);
71
static gboolean _write_event(GIOChannel *source,
72
GIOCondition condition, gpointer data)
74
GIOSocket *s = (GIOSocket*)data;
75
return s->write_event(condition);
78
bool write_event(GIOCondition condition)
83
assert(condition & G_IO_OUT);
85
if (!outp && !outbuf.empty())
86
outp = outbuf.front().c_str();
89
return (write_tag = 0);
91
unsigned len = strlen(outp);
93
GIOError e = g_io_channel_write(con, (char*)outp, len, &n);
94
if (e == G_IO_ERROR_NONE)
100
return outbuf.empty() ? (write_tag = 0) : 1;
108
bool read_event(GIOCondition condition)
113
if (condition & G_IO_HUP)
118
std::cerr << "Connection terminated." << std::endl;
123
if (condition & G_IO_IN)
126
GIOError e = g_io_channel_read(con, buf, sizeof(buf) - 1, &n);
127
if (e == G_IO_ERROR_NONE)
130
char *lineend, *cur = buf;
131
while ((lineend = strchr(cur, '\n')))
150
int read_tag, write_tag;
153
std::list<string> outbuf;