1 // 2 // Copyright (C) 2020 The Android Open Source Project 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 #pragma once 17 18 #include <deque> 19 #include <vector> 20 21 struct lws; 22 23 namespace cuttlefish { 24 25 class WebSocketHandler { 26 public: 27 WebSocketHandler(struct lws* wsi); 28 virtual ~WebSocketHandler() = default; 29 30 virtual void OnReceive(const uint8_t* msg, size_t len, bool binary) = 0; OnReceive(const uint8_t * msg,size_t len,bool binary,bool is_final)31 virtual void OnReceive(const uint8_t* msg, size_t len, bool binary, 32 [[maybe_unused]] bool is_final) { 33 OnReceive(msg, len, binary); 34 } 35 virtual void OnConnected() = 0; 36 virtual void OnClosed() = 0; 37 38 void EnqueueMessage(const uint8_t* data, size_t len, bool binary = false); 39 void EnqueueMessage(const char* data, size_t len, bool binary = false) { 40 EnqueueMessage(reinterpret_cast<const uint8_t*>(data), len, binary); 41 } 42 void Close(); 43 bool OnWritable(); 44 45 private: 46 struct WsBuffer { WsBufferWsBuffer47 WsBuffer(std::vector<uint8_t> data, bool binary) 48 : data(std::move(data)), binary(binary) {} 49 std::vector<uint8_t> data; 50 bool binary; 51 }; 52 53 void WriteWsBuffer(WsBuffer& ws_buffer); 54 55 struct lws* wsi_; 56 bool close_ = false; 57 std::deque<WsBuffer> buffer_queue_; 58 }; 59 60 class WebSocketHandlerFactory { 61 public: 62 virtual ~WebSocketHandlerFactory() = default; 63 virtual std::shared_ptr<WebSocketHandler> Build(struct lws* wsi) = 0; 64 }; 65 66 } // namespace cuttlefish 67