Replies: 3 comments
-
Record all channels, traverse to send. |
Beta Was this translation helpful? Give feedback.
0 replies
-
#include "WebSocketServer.h"
using namespace hv;
class ChannelMgr {
public:
void addChannel(const WebSocketChannelPtr& channel) {
std::lock_guard<std::mutex> locker(mutex_);
channels[channel->id()] = channel;
}
void removeChannel(const WebSocketChannelPtr& channel) {
std::lock_guard<std::mutex> locker(mutex_);
channels.erase(channel->id());
}
int foreachChannel(std::function<void(const WebSocketChannelPtr& channel)> fn) {
std::lock_guard<std::mutex> locker(mutex_);
for (auto& pair : channels) {
fn(pair.second);
}
return channels.size();
}
// broadcast thread-safe
int broadcast(const void* data, int size) {
return foreachChannel([data, size](const WebSocketChannelPtr& channel) {
channel->send((const char*)data, size);
});
}
int broadcast(const std::string& str) {
return broadcast(str.data(), str.size());
}
private:
// id => SocketChannelPtr
std::map<int, WebSocketChannelPtr> channels;
std::mutex mutex_;
};
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: %s port\n", argv[0]);
return -10;
}
int port = atoi(argv[1]);
HttpService http;
http.GET("/ping", [](const HttpContextPtr& ctx) {
return ctx->send("pong");
});
WebSocketService ws;
ChannelMgr mgr;
ws.onopen = [&mgr](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) {
printf("onopen: GET %s\n", req->Path().c_str());
mgr.addChannel(channel);
};
ws.onmessage = [&mgr](const WebSocketChannelPtr& channel, const std::string& msg) {
printf("onmessage: %d\n", (int)msg.size());
mgr.broadcast(msg);
};
ws.onclose = [&mgr](const WebSocketChannelPtr& channel) {
printf("onclose\n");
mgr.removeChannel(channel);
};
websocket_server_t server;
server.port = port;
server.service = &http;
server.ws = &ws;
websocket_server_run(&server);
return 0;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
komnotmr
-
Thank you! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is there examples of sending broadcast messages through websockets?
Beta Was this translation helpful? Give feedback.
All reactions