Simple WebSocket server library.

Dependents:   WebSocketServerTest

WebSocketServer.cpp

Committer:
flatbird
Date:
2015-04-06
Revision:
2:db41b4e0d64b
Parent:
0:a816c25e83ed

File content as of revision 2:db41b4e0d64b:

#include "WebSocketServer.h"
#include "WebSocketConnection.h"

WebSocketServer::WebSocketServer()
{
}

WebSocketServer::~WebSocketServer()
{
}

bool WebSocketServer::init(int port)
{
	mTCPSocketServer.set_blocking(true);

	int ret = mTCPSocketServer.bind(port);
	if (ret != 0) {
		printf("ERROR: Failed to bind %d\r\n", ret);
		return false;
	}
	ret = mTCPSocketServer.listen();
	if (ret != 0) {
		printf("ERROR: Failed to listen %d\r\n", ret);
		return false;
	}

	return true;
}

void WebSocketServer::run()
{
	WebSocketConnection connection(this);

	while (true) {
		// printf("accepting\r\n");
		int ret = mTCPSocketServer.accept(connection.getTCPSocketConnection());
		if (ret != 0) {
			continue;
		}
		connection.run();
	}
}

void WebSocketServer::setHandler(const char* path, WebSocketHandler* handler)
{
	mHandlers[path] = handler;
}

WebSocketHandler* WebSocketServer::getHandler(const char* path)
{
	WebSocketHandlerContainer::iterator it;

	it = mHandlers.find(path);
	if (it != mHandlers.end()) {
		return it->second;
	}
	return NULL;
}