WebSocketChannel.h 1.3 KB

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