1 #include <samchon/protocol/IWebServer.hpp> 4 #include <boost/asio.hpp> 5 #include <boost/uuid/sha1.hpp> 7 #include <samchon/ByteArray.hpp> 8 #include <samchon/WeakString.hpp> 9 #include <samchon/library/Base64.hpp> 10 #include <samchon/library/StringUtil.hpp> 21 IWebServer::IWebServer()
30 boost::system::error_code error;
31 boost::asio::io_service ioService;
32 unique_ptr<boost::asio::ip::tcp::endpoint> endPoint;
36 string &myIP =
MY_IP();
38 if (myIP.empty() ==
true)
40 endPoint.reset(
new boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),
PORT()) );
44 endPoint.reset(
new boost::asio::ip::tcp::endpoint( boost::asio::ip::address::from_string(myIP),
PORT() ) );
46 acceptor =
new boost::asio::ip::tcp::acceptor(ioService, *endPoint);
51 Socket *socket =
new Socket(ioService);
64 if (handshake(socket) ==
true)
76 auto IWebServer::handshake(Socket *socket)
const ->
bool 79 boost::system::error_code error;
81 byteArray.assign(1000, NULL);
83 socket->read_some(boost::asio::buffer(byteArray), error);
87 string &header = byteArray.
read<
string>();
90 wstr = wstr.
between(
"Sec-WebSocket-Key:",
"\n").trim();
91 if(wstr.find(
"\r") != string::npos)
92 wstr = wstr.between(
"",
"\r");
95 StringUtil::substitute
98 "HTTP/1.1 101 Switching Protocols\r\n" +
99 "Upgrade: websocket\r\n" +
100 "Connection: Upgrade\r\n" +
101 "Sec-WebSocket-Accept: {1}\r\n" +
104 calculateCertificationKey(wstr.str())
107 socket->write_some(boost::asio::buffer(handshake), error);
113 auto IWebServer::calculateCertificationKey(
const string &key64)
const ->
string 115 string acceptKey = key64 +
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
117 boost::uuids::detail::sha1 hash;
118 hash.process_bytes(acceptKey.c_str(), acceptKey.size());
121 unsigned int digest[5];
122 hash.get_digest(digest);
124 for (
size_t index = 0; index < 5; index++)
130 return Base64::encode(bytes);
An interface of a physical server.
virtual void open() override
Open the web-socket server.
virtual auto PORT() const -> int=NULL
Port number of the server.
auto read() const -> T
Read data.
void writeReversely(const T &val)
Write a data.
virtual auto MY_IP() const -> std::string
(optional) Server's IP
Package of network protocol and libraries.
virtual void addClient(Socket *)=0
Handling connection of a physical client.
auto between(const WeakString &start={}, const WeakString &end={}) const -> WeakString
Generates a substring.
Top level namespace of products built from samchon.
A string class only references characeters, reference only.
Acceptor * acceptor
An acceptor for clients.