IXWebSocket/ixwebsocket/IXWebSocketServer.cpp

105 lines
2.7 KiB
C++
Raw Normal View History

2018-12-30 08:15:27 +01:00
/*
* IXWebSocketServer.cpp
* Author: Benjamin Sergeant
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
*/
#include "IXWebSocketServer.h"
#include "IXWebSocketTransport.h"
#include "IXWebSocket.h"
#include "IXSocketConnect.h"
2019-01-06 05:38:43 +01:00
#include "IXNetSystem.h"
#include <sstream>
2019-01-01 22:47:25 +01:00
#include <future>
2019-01-02 02:13:26 +01:00
#include <string.h>
2018-12-30 08:15:27 +01:00
namespace ix
{
2019-01-04 03:33:08 +01:00
const int WebSocketServer::kDefaultHandShakeTimeoutSecs(3); // 3 seconds
WebSocketServer::WebSocketServer(int port,
const std::string& host,
int backlog,
2019-01-04 03:33:08 +01:00
size_t maxConnections,
int handshakeTimeoutSecs) : SocketServer(port, host, backlog, maxConnections),
_handshakeTimeoutSecs(handshakeTimeoutSecs)
2018-12-30 08:15:27 +01:00
{
}
WebSocketServer::~WebSocketServer()
{
stop();
2018-12-30 08:15:27 +01:00
}
void WebSocketServer::stop()
{
auto clients = getClients();
for (auto client : clients)
{
client->close();
}
SocketServer::stop();
}
void WebSocketServer::setOnConnectionCallback(const OnConnectionCallback& callback)
{
_onConnectionCallback = callback;
}
void WebSocketServer::handleConnection(int fd)
{
2019-01-01 22:53:13 +01:00
std::shared_ptr<WebSocket> webSocket(new WebSocket);
_onConnectionCallback(webSocket);
webSocket->disableAutomaticReconnection();
// Add this client to our client set
{
std::lock_guard<std::mutex> lock(_clientsMutex);
_clients.insert(webSocket);
}
2019-01-01 22:47:25 +01:00
2019-01-04 03:33:08 +01:00
auto status = webSocket->connectToSocket(fd, _handshakeTimeoutSecs);
if (status.success)
{
// Process incoming messages and execute callbacks
// until the connection is closed
webSocket->run();
}
else
2019-01-01 22:47:25 +01:00
{
std::stringstream ss;
ss << "WebSocketServer::handleConnection() error: "
<< status.http_status
<< " error: "
<< status.errorStr;
logError(ss.str());
2019-01-01 22:47:25 +01:00
}
// Remove this client from our client set
{
std::lock_guard<std::mutex> lock(_clientsMutex);
if (_clients.erase(webSocket) != 1)
{
logError("Cannot delete client");
}
}
logInfo("WebSocketServer::handleConnection() done");
}
2019-01-01 22:47:25 +01:00
std::set<std::shared_ptr<WebSocket>> WebSocketServer::getClients()
{
std::lock_guard<std::mutex> lock(_clientsMutex);
return _clients;
2018-12-30 08:15:27 +01:00
}
size_t WebSocketServer::getConnectedClientsCount()
{
return getClients().size();
}
2018-12-30 08:15:27 +01:00
}