WebSocketChannel.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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, bool fin = true) {
  18. return send(msg.c_str(), msg.size(), opcode, fin);
  19. }
  20. int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true) {
  21. int fragment = 0xFFFF; // 65535
  22. if (len > fragment) {
  23. return send(buf, len, fragment, opcode);
  24. }
  25. return send_(buf, len, opcode, fin);
  26. }
  27. // websocket fragment
  28. // send(p, fragment, opcode, false) ->
  29. // send(p, fragment, WS_OPCODE_CONTINUE, false) ->
  30. // ... ->
  31. // send(p, remain, WS_OPCODE_CONTINUE, true)
  32. int send(const char* buf, int len, int fragment, enum ws_opcode opcode = WS_OPCODE_BINARY) {
  33. if (len <= fragment) {
  34. return send_(buf, len, opcode, true);
  35. }
  36. // first fragment
  37. int nsend = send_(buf, fragment, opcode, false);
  38. if (nsend < 0) return nsend;
  39. const char* p = buf + fragment;
  40. int remain = len - fragment;
  41. while (remain > fragment) {
  42. nsend = send_(p, fragment, WS_OPCODE_CONTINUE, false);
  43. if (nsend < 0) return nsend;
  44. p += fragment;
  45. remain -= fragment;
  46. }
  47. // last fragment
  48. nsend = send_(p, remain, WS_OPCODE_CONTINUE, true);
  49. if (nsend < 0) return nsend;
  50. return len;
  51. }
  52. protected:
  53. int send_(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true) {
  54. bool has_mask = false;
  55. char mask[4] = {0};
  56. if (type == WS_CLIENT) {
  57. has_mask = true;
  58. *(int*)mask = rand();
  59. }
  60. int frame_size = ws_calc_frame_size(len, has_mask);
  61. std::lock_guard<std::mutex> locker(mutex_);
  62. if (sendbuf_.len < frame_size) {
  63. sendbuf_.resize(ceil2e(frame_size));
  64. }
  65. ws_build_frame(sendbuf_.base, buf, len, mask, has_mask, opcode, fin);
  66. return write(sendbuf_.base, frame_size);
  67. }
  68. private:
  69. Buffer sendbuf_;
  70. std::mutex mutex_;
  71. };
  72. }
  73. typedef std::shared_ptr<hv::WebSocketChannel> WebSocketChannelPtr;
  74. #endif // HV_WEBSOCKET_CHANNEL_H_