使用 libevent 广播 TCP 服务器

发布于 2024-11-17 18:43:50 字数 967 浏览 1 评论 0原文

我正在寻找一些基于 libevent 的简单 TCP 服务器的示例代码,它将传入的消息广播到所有连接的客户端。在网络上我只找到了回显消息的 TCP 服务器。

如果找到一个 echo 示例,则位于本页底部 http://www .wangafu.net/~nickm/libevent-book/Ref8_listener.html

我确信更改本网站提供的代码并不困难,以便将消息广播到所有连接的客户端,但我不知道怎么办。

有人可以建议我吗?

编辑:是的,某种聊天服务器。看来我需要这样做:

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);
}

但我不能让它发挥作用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的背包 2024-11-24 18:43:50

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文