1
0

WebSocketChannel.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 = WS_OPCODE_TEXT) {
  17. return send(msg.c_str(), msg.size(), opcode);
  18. }
  19. int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY) {
  20. bool has_mask = false;
  21. char mask[4] = {0};
  22. if (type == WS_CLIENT) {
  23. has_mask = true;
  24. *(int*)mask = rand();
  25. }
  26. int frame_size = ws_calc_frame_size(len, has_mask);
  27. if (sendbuf.len < frame_size) {
  28. sendbuf.resize(ceil2e(frame_size));
  29. }
  30. ws_build_frame(sendbuf.base, buf, len, mask, has_mask, opcode);
  31. return write(sendbuf.base, frame_size);
  32. }
  33. private:
  34. Buffer sendbuf;
  35. };
  36. }
  37. typedef std::shared_ptr<hv::WebSocketChannel> WebSocketChannelPtr;
  38. #endif // HV_WEBSOCKET_CHANNEL_H_