use shared_ptr

This commit is contained in:
Benjamin Sergeant 2019-01-01 13:53:13 -08:00
parent 5ea2028c22
commit de66a87a7c
3 changed files with 14 additions and 13 deletions

View File

@ -21,10 +21,10 @@ int main(int argc, char** argv)
ix::WebSocketServer server(port);
server.setOnConnectionCallback(
[&server](ix::WebSocket& webSocket)
[&server](std::shared_ptr<ix::WebSocket> webSocket)
{
webSocket.setOnMessageCallback(
[&webSocket, &server](ix::WebSocketMessageType messageType,
webSocket->setOnMessageCallback(
[webSocket, &server](ix::WebSocketMessageType messageType,
const std::string& str,
size_t wireSize,
const ix::WebSocketErrorInfo& error,
@ -49,7 +49,7 @@ int main(int argc, char** argv)
for (auto&& client : server.getClients())
{
if (client != &webSocket)
if (client != webSocket)
{
client->send(str);
}

View File

@ -132,13 +132,13 @@ namespace ix
//
void WebSocketServer::handleConnection(int fd)
{
ix::WebSocket webSocket;
std::shared_ptr<WebSocket> webSocket(new WebSocket);
_onConnectionCallback(webSocket);
_clients.insert(&webSocket);
_clients.insert(webSocket);
webSocket.start();
auto status = webSocket.connectToSocket(fd);
webSocket->start();
auto status = webSocket->connectToSocket(fd);
if (!status.success)
{
std::cerr << "WebSocketServer::handleConnection() error: "
@ -148,13 +148,13 @@ namespace ix
}
// We can probably do better than this busy loop, with a condition variable.
while (webSocket.isConnected())
while (webSocket->isConnected())
{
std::chrono::duration<double, std::milli> wait(10);
std::this_thread::sleep_for(wait);
}
_clients.erase(&webSocket);
_clients.erase(webSocket);
std::cerr << "WebSocketServer::handleConnection() done" << std::endl;
}

View File

@ -12,12 +12,13 @@
#include <thread>
#include <mutex>
#include <functional>
#include <memory>
#include "IXWebSocket.h"
namespace ix
{
using OnConnectionCallback = std::function<void(WebSocket&)>;
using OnConnectionCallback = std::function<void(std::shared_ptr<WebSocket>)>;
class WebSocketServer {
public:
@ -30,7 +31,7 @@ namespace ix
void run();
// FIXME: need mutex
std::set<WebSocket*> getClients() { return _clients; }
std::set<std::shared_ptr<WebSocket>> getClients() { return _clients; }
private:
void handleConnection(int fd);
@ -43,6 +44,6 @@ namespace ix
// socket for accepting connections
int _serverFd;
std::set<WebSocket*> _clients;
std::set<std::shared_ptr<WebSocket>> _clients;
};
}