Web Socket Client
Fork of WebSocketClient by
Diff: Websocket.cpp
- Revision:
- 8:860d3b8e21f9
- Parent:
- 7:4567996414a5
--- a/Websocket.cpp Fri Feb 08 12:33:04 2013 +0000 +++ b/Websocket.cpp Thu Jun 15 20:18:14 2017 +0000 @@ -1,10 +1,11 @@ #include "Websocket.h" +#include "DNSClient.h" #define MAX_TRY_WRITE 20 #define MAX_TRY_READ 10 //Debug is disabled by default -#if 0 +#if 1 #define DBG(x, ...) std::printf("[WebSocket : DBG]"x"\r\n", ##__VA_ARGS__); #define WARN(x, ...) std::printf("[WebSocket : WARN]"x"\r\n", ##__VA_ARGS__); #define ERR(x, ...) std::printf("[WebSocket : ERR]"x"\r\n", ##__VA_ARGS__); @@ -16,9 +17,12 @@ #define INFO(x, ...) printf("[WebSocket : INFO]"x"\r\n", ##__VA_ARGS__); -Websocket::Websocket(char * url) { +Websocket::Websocket(NetworkStack *ns, char * url) { + m_ns = ns; fillFields(url); - socket.set_blocking(false, 400); + socket.open(ns); + socket.set_blocking(false); + socket.set_timeout(400); } void Websocket::fillFields(char * url) { @@ -115,13 +119,24 @@ bool Websocket::connect() { + DNSClient dns(m_ns); char cmd[200]; - - while (socket.connect(host, port) < 0) { - ERR("Unable to connect to (%s) on port (%d)", host, port); + + if (!dns.lookup(host)) { + ERR("Websocket: Unable to resolve hostname (%s)", host); wait(0.2); + connected = false; return false; } + + while (socket.connect(dns.get_ip_address(), port) < 0) { + ERR("Websocket: Unable to connect to (%s) on port (%d)", host, port); + wait(0.2); + connected = false; + return false; + } + + connected = true; // sent http header to upgrade to the ws protocol sprintf(cmd, "GET %s HTTP/1.1\r\n", path); @@ -240,19 +255,22 @@ return false; } - if(!socket.is_connected()) + if(!connected) { WARN("Connection was closed by server"); return false; } - socket.set_blocking(false, 1); - if (socket.receive(&opcode, 1) != 1) { - socket.set_blocking(false, 2000); + socket.set_blocking(false); + socket.set_timeout(1); + if (socket.recv(&opcode, 1) != 1) { + socket.set_blocking(false); + socket.set_timeout(2000); return false; } - socket.set_blocking(false, 2000); + socket.set_blocking(false); + socket.set_timeout(2000); if (opcode == 0x81) break; @@ -312,7 +330,7 @@ } bool Websocket::is_connected() { - return socket.is_connected(); + return connected; } char* Websocket::getPath() { @@ -324,13 +342,13 @@ for (int j = 0; j < MAX_TRY_WRITE; j++) { - if(!socket.is_connected()) + if(!connected) { WARN("Connection was closed by server"); break; } - if ((res = socket.send_all(str + idx, len - idx)) == -1) + if ((res = socket.send(str + idx, len - idx)) == -1) continue; idx += res; @@ -347,7 +365,7 @@ for (int j = 0; j < MAX_TRY_WRITE; j++) { - if ((res = socket.receive_all(str + idx, len - idx)) == -1) + if ((res = socket.recv(str + idx, len - idx)) == -1) continue; idx += res;