0

I am looking for some sample code of a dead simple libevent-based TCP-Server which broadcasts incoming Messages to all connected clients. On the Web I only found TCP-Servers which echoes back messages.

One echo example if found is on the bottom of this page http://www.wangafu.net/~nickm/libevent-book/Ref8_listener.html

I am sure that its not so difficult to change the code provided on this Site, so that messages are brodcast to all connected clients, but I don't know how.

Could someone advise me?

EDIT: Yes, some kind of a chat server. It seams i need to do sth like this:

void server_read_cb(struct bufferevent *bev, void *data)
{
       struct evbuffer *input = bufferevent_get_input(bev);
       struct evbuffer *output = bufferevent_get_output(bev);

       char *mem = malloc(len); /* XXX: check for malloc failure */

       evbuffer_remove(input, mem, len);
       "for every connection conn" {
           /* XXX you'll need to implement a real connection list;
              the above isn't real C. */
               evbuffer_add(bufferevent_get_output(conn), mem, len);
       }
       free(mem);
}

But i can't put this to work.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Filipe Santos
  • 1,629
  • 3
  • 18
  • 27
  • Does a TCP-Server keep track of all open TCP-Clients that are connected to it at any given time? I would think that managing all of those connections would require more resources than simply broadcasting messages out on the "listen wire". –  Jul 11 '11 at 18:09
  • From looking at the sample code you linked, I'd *guess* the server has the option to record what devices are listening to it whenever a connection is made, then remove that device from the list of listeners whenever it receives an error on `accept_error_cb`. The `WangAFu` article seems to have left the particular implementation you seek up to the Programmer. –  Jul 11 '11 at 18:12

1 Answers1

1

Seems you want something similar to a chat server. One example is here. Basically, when you receive data from one connection, you just go through the list of connections and send that same data to each one (including/excluding the original).

Ioan
  • 2,382
  • 18
  • 32