Simple WebSocket server library.

Dependents:   WebSocketServerTest

Committer:
flatbird
Date:
Mon Mar 16 10:13:30 2015 +0000
Revision:
0:a816c25e83ed
WebSocketServer library

Who changed what in which revision?

UserRevisionLine numberNew contents of line
flatbird 0:a816c25e83ed 1 #include "WebSocketServer.h"
flatbird 0:a816c25e83ed 2 #include "WebSocketConnection.h"
flatbird 0:a816c25e83ed 3
flatbird 0:a816c25e83ed 4 WebSocketServer::WebSocketServer()
flatbird 0:a816c25e83ed 5 {
flatbird 0:a816c25e83ed 6 }
flatbird 0:a816c25e83ed 7
flatbird 0:a816c25e83ed 8 WebSocketServer::~WebSocketServer()
flatbird 0:a816c25e83ed 9 {
flatbird 0:a816c25e83ed 10 }
flatbird 0:a816c25e83ed 11
flatbird 0:a816c25e83ed 12 bool WebSocketServer::init(int port)
flatbird 0:a816c25e83ed 13 {
flatbird 0:a816c25e83ed 14 mTCPSocketServer.set_blocking(true);
flatbird 0:a816c25e83ed 15
flatbird 0:a816c25e83ed 16 int ret = mTCPSocketServer.bind(port);
flatbird 0:a816c25e83ed 17 if (ret != 0) {
flatbird 0:a816c25e83ed 18 printf("ERROR: Failed to bind %d\r\n", ret);
flatbird 0:a816c25e83ed 19 return false;
flatbird 0:a816c25e83ed 20 }
flatbird 0:a816c25e83ed 21 ret = mTCPSocketServer.listen();
flatbird 0:a816c25e83ed 22 if (ret != 0) {
flatbird 0:a816c25e83ed 23 printf("ERROR: Failed to listen %d\r\n", ret);
flatbird 0:a816c25e83ed 24 return false;
flatbird 0:a816c25e83ed 25 }
flatbird 0:a816c25e83ed 26
flatbird 0:a816c25e83ed 27 return true;
flatbird 0:a816c25e83ed 28 }
flatbird 0:a816c25e83ed 29
flatbird 0:a816c25e83ed 30 void WebSocketServer::run()
flatbird 0:a816c25e83ed 31 {
flatbird 0:a816c25e83ed 32 WebSocketConnection connection(this);
flatbird 0:a816c25e83ed 33
flatbird 0:a816c25e83ed 34 while (true) {
flatbird 0:a816c25e83ed 35 // printf("accepting\r\n");
flatbird 0:a816c25e83ed 36 int ret = mTCPSocketServer.accept(connection.getTCPSocketConnection());
flatbird 0:a816c25e83ed 37 if (ret != 0) {
flatbird 0:a816c25e83ed 38 continue;
flatbird 0:a816c25e83ed 39 }
flatbird 0:a816c25e83ed 40 connection.run();
flatbird 0:a816c25e83ed 41 }
flatbird 0:a816c25e83ed 42 }
flatbird 0:a816c25e83ed 43
flatbird 0:a816c25e83ed 44 void WebSocketServer::setHandler(const char* path, WebSocketHandler* handler)
flatbird 0:a816c25e83ed 45 {
flatbird 0:a816c25e83ed 46 mHandlers[path] = handler;
flatbird 0:a816c25e83ed 47 }
flatbird 0:a816c25e83ed 48
flatbird 0:a816c25e83ed 49 WebSocketHandler* WebSocketServer::getHandler(const char* path)
flatbird 0:a816c25e83ed 50 {
flatbird 0:a816c25e83ed 51 WebSocketHandlerContainer::iterator it;
flatbird 0:a816c25e83ed 52
flatbird 0:a816c25e83ed 53 it = mHandlers.find(path);
flatbird 0:a816c25e83ed 54 if (it != mHandlers.end()) {
flatbird 0:a816c25e83ed 55 return it->second;
flatbird 0:a816c25e83ed 56 }
flatbird 0:a816c25e83ed 57 return NULL;
flatbird 0:a816c25e83ed 58 }
flatbird 0:a816c25e83ed 59