WebSocketChannel.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #ifndef HV_WEBSOCKET_CHANNEL_H_
  2. #define HV_WEBSOCKET_CHANNEL_H_
  3. #include "Channel.h"
  4. #include "wsdef.h"
  5. #include "hmath.h"
  6. namespace hv {
  7. class WebSocketChannel : public SocketChannel {
  8. public:
  9. ws_session_type type;
  10. WebSocketChannel(hio_t* io, ws_session_type type = WS_CLIENT)
  11. : SocketChannel(io)
  12. , type(type)
  13. {}
  14. ~WebSocketChannel() {}
  15. // isConnected, send, close
  16. int send(const std::string& msg, enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT)) {
  17. bool has_mask = false;
  18. char mask[4] = {0};
  19. if (type == WS_CLIENT) {
  20. has_mask = true;
  21. *(int*)mask = rand();
  22. }
  23. int frame_size = ws_calc_frame_size(msg.size(), has_mask);
  24. if (sendbuf.len < frame_size) {
  25. sendbuf.resize(ceil2e(frame_size));
  26. }
  27. ws_build_frame(sendbuf.base, msg.c_str(), msg.size(), mask, has_mask, opcode);
  28. Buffer buf(sendbuf.base, frame_size);
  29. return write(&buf);
  30. }
  31. private:
  32. Buffer sendbuf;
  33. };
  34. }
  35. typedef std::shared_ptr<hv::WebSocketChannel> WebSocketChannelPtr;
  36. #endif // HV_WEBSOCKET_CHANNEL_H_