Reputation: 105
Websocket protocol has completely changed since version 8. Now the incoming messages from the browser are in a very different format and for me is really complicated.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
Here is what I found from https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-17
Does anybody know how to implement the server side read in c++ or c#? Or do you have a link to an example that is already working?
I know this server is correct but I need a code: http://websocket.org/echo.html
Upvotes: 2
Views: 919
Reputation: 5353
There's a great C++ WebSocket library here that supports hybi-17 (the latest revision), its header-only and uses just boost. It comes with example code and documentation: http://vinniefalco.github.io/
Here's a complete program that sends a message to the echo server:
#include <beast/websocket.hpp>
#include <beast/buffers_debug.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>
int main()
{
// Normal boost::asio setup
std::string const host = "echo.websocket.org";
boost::asio::io_service ios;
boost::asio::ip::tcp::resolver r(ios);
boost::asio::ip::tcp::socket sock(ios);
boost::asio::connect(sock,
r.resolve(boost::asio::ip::tcp::resolver::query{host, "80"}));
using namespace beast::websocket;
// WebSocket connect and send message using beast
stream<boost::asio::ip::tcp::socket&> ws(sock);
ws.handshake(host, "/");
ws.write(boost::asio::buffer("Hello, world!"));
// Receive WebSocket message, print and close using beast
beast::streambuf sb;
opcode op;
ws.read(op, sb);
ws.close(close_code::normal);
std::cout <<
beast::debug::buffers_to_string(sb.data()) << "\n";
}
Upvotes: 3
Reputation: 42175
I've written a C++ server. See WsProtocol80::Read()
for how to read hybi-17 messages. Note that the server uses custom string and socket classes so would be non-trivial to reuse but you should be able to easily follow what data is being read/written.
Feel free to ask any questions about specific parts of the code.
This wiki post may also be of interest.
Upvotes: 1