使用 libevent 广播 TCP 服务器
我正在寻找一些基于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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).